answer
stringlengths
17
10.2M
package nl.mvdr.tinustris.model; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import nl.mvdr.tinustris.input.InputStateHistory; /** * Representation of the game state for a single Tetris player. * * @author Martijn van de Rijdt */ @EqualsAndHashCode @Getter public class GameState { /** height of the vanish zone. */ private static final int VANISH_ZONE_HEIGHT = 2; /** Minimum width of a Tetris grid. */ private static final int MIN_WIDTH = 4; /** Minimum height of a Tetris grid. */ private static final int MIN_HEIGHT = 4 + VANISH_ZONE_HEIGHT; /** Default width of a Tetris grid. */ public static final int DEFAULT_WIDTH = 10; /** Default height of a Tetris grid. */ public static final int DEFAULT_HEIGHT = 22; /** Number of frames a line stays on screen before it disappears. */ public static final int FRAMES_LINES_STAY = 25; /** * The basin of blocks. * * Element (i, j) of the grid is represented by grid[i * width + j]. If the element is null, that space in the grid * is empty; otherwise it contains a block. The specific Tetromino value indicates the tetromino that the block was * originally a part of, which may affect how it is represented graphically. * * The current block (that the payer is still controlling as it falls) is not contained in the grid. * * Note that the top two rows of the grid should not be visible. * * The value of this field is not modified; in fact it should preferably be an unmodifiable list. */ @NonNull private final List<Tetromino> grid; /** Width of the grid. */ private final int width; /** Current block. May be null, if the game is in the process of showing a cutscene (like a disappearing line). */ private final Tetromino currentBlock; /** The current block's location. May be null if currentBlock is null as well. */ private final Point currentBlockLocation; /** The current block's orientation. May be null if currentBlock is null as well. */ private final Orientation currentBlockOrientation; /** The next block in line. */ @NonNull // TODO replace by a queue of blocks, in case we want to be able to display multiple "next" blocks private final Tetromino nextBlock; /** The number of frames since the last time the active block was moved down. */ private final int numFramesSinceLastDownMove; /** Input state history, up until and including the current frame. */ @NonNull private final InputStateHistory inputStateHistory; /** Block counter. Equals the number of blocks that have been dropped. */ private final int blockCounter; /** Number of lines that have been scored in this game. */ private final int lines; /** * The number of frames until the current lines disappear. * * After the player completes a line, the game pauses for a short time while the line stays on a the screen for a * short while before it disappears and the next active block appears. This variable indicates the number of frames * that still remain. It is zero if there are currently no full lines in the grid. */ private final int numFramesUntilLinesDisappear; /** Constructor for a (new) game with a completely empty grid of default size. */ public GameState() { this(DEFAULT_WIDTH, DEFAULT_HEIGHT); } /** * Constructor for a (new) game with a completely empty grid. * * @param width * width of the basin, should be at least 1 * @param height * height of the basin, should be at least 3 */ public GameState(int width, int height) { super(); checkWidth(width); checkHeight(height); this.width = width; ArrayList<Tetromino> tempGrid = new ArrayList<>(width * height); while (tempGrid.size() != width * height) { tempGrid.add(null); } this.grid = Collections.unmodifiableList(tempGrid); this.currentBlock = null; this.currentBlockLocation = null; this.currentBlockOrientation = null; this.nextBlock = Tetromino.I; // TODO determine randomly? this.numFramesSinceLastDownMove = 0; this.inputStateHistory = new InputStateHistory(); this.blockCounter = 0; this.lines = 0; this.numFramesUntilLinesDisappear = 0; } /** * Constructor. * * @param grid * grid * @param width * width of the grid * @param currentBlock * current block * @param currentBlockLocation * location of the current block * @param currentBlockOrientation * orientation of the current block * @param nextBlock * next block */ public GameState(@NonNull List<Tetromino> grid, int width, Tetromino currentBlock, Point currentBlockLocation, Orientation currentBlockOrientation, @NonNull Tetromino nextBlock) { this(grid, width, currentBlock, currentBlockLocation, currentBlockOrientation, nextBlock, 0, new InputStateHistory(), 0, 0, 0); } /** * Convenience constructor. * * @param grid * grid * @param width * width of the grid * @param currentBlock * current block * @param currentBlockLocation * location of the current block * @param currentBlockOrientation * orientation of the current block * @param nextBlock * next block * @param numFramesSinceLastTick * number of frames since the last tick * @param inputStateHistory * history of the input state; includes the current frame * @param blockCounter * number of blocks that have been dropped * @param lines * number of lines that have been scored in this game */ public GameState(@NonNull List<Tetromino> grid, int width, Tetromino currentBlock, Point currentBlockLocation, Orientation currentBlockOrientation, @NonNull Tetromino nextBlock, int numFramesSinceLastTick, InputStateHistory inputStateHistory, int blockCounter, int lines) { this(grid, width, currentBlock, currentBlockLocation, currentBlockOrientation, nextBlock, numFramesSinceLastTick, inputStateHistory, blockCounter, lines, 0); } /** * Constructor. * * @param grid * grid * @param width * width of the grid * @param currentBlock * current block * @param currentBlockLocation * location of the current block * @param currentBlockOrientation * orientation of the current block * @param nextBlock * next block * @param numFramesSinceLastTick * number of frames since the last tick * @param inputStateHistory * history of the input state; includes the current frame * @param blockCounter * number of blocks that have been dropped * @param lines * number of lines that have been scored in this game * @param numFramesUntilLinesDisappear * number of remaining frames until lines disappear */ public GameState(@NonNull List<Tetromino> grid, int width, Tetromino currentBlock, Point currentBlockLocation, Orientation currentBlockOrientation, @NonNull Tetromino nextBlock, int numFramesSinceLastTick, InputStateHistory inputStateHistory, int blockCounter, int lines, int numFramesUntilLinesDisappear) { super(); checkWidth(width); if (grid.size() % width != 0) { throw new IllegalArgumentException("Unexpected grid size, should be a multiple of width " + width + ", was: " + grid.size()); } this.grid = grid; this.width = width; checkHeight(getHeight()); this.currentBlock = currentBlock; this.currentBlockLocation = currentBlockLocation; this.currentBlockOrientation = currentBlockOrientation; this.nextBlock = nextBlock; this.numFramesSinceLastDownMove = numFramesSinceLastTick; this.inputStateHistory = inputStateHistory; this.blockCounter = blockCounter; this.lines = lines; this.numFramesUntilLinesDisappear = numFramesUntilLinesDisappear; } /** * Constructor. * * If currentBlock is not null, it is spawned at the default spawn location. * * @param grid * grid * @param width * width of the grid * @param currentBlock * current block * @param nextBlock * next block */ public GameState(@NonNull List<Tetromino> grid, int width, Tetromino currentBlock, @NonNull Tetromino nextBlock) { this(grid, width, currentBlock, currentBlock == null ? null : getBlockSpawnLocation(width, computeHeight(grid, width)), Orientation.getDefault(), nextBlock); } /** * Computes the spawn location for new blocks. * * @param width width of the grid * @param height height of the grid * @return spawn location */ private static Point getBlockSpawnLocation(int width, int height) { return new Point(width / 2 - 2, height - 4 - VANISH_ZONE_HEIGHT); } /** * Computes the spawn location for new blocks. * * @return spawn location */ public Point getBlockSpawnLocation() { return getBlockSpawnLocation(width, getHeight()); } private void checkWidth(int w) { if (w < MIN_WIDTH) { throw new IllegalArgumentException("width should be at least " + MIN_WIDTH + ", was: " + w); } } private void checkHeight(int height) { if (height < MIN_HEIGHT) { throw new IllegalArgumentException("height should be at least " + MIN_HEIGHT + ", was: " + height); } } /** @return the grid's height */ public int getHeight() { return computeHeight(this.grid, this.width); } /** * Computes the grid's height. * * @param grid * grid * @param width * width of the grid * @return the grind's height */ private static int computeHeight(List<Tetromino> grid, int width) { if (width == 0) { throw new IllegalArgumentException("Width must be more than zero."); } return grid.size() / width; } /** * Returns the block in the grid at index i, j. Does not take the player's currently controlled block into account. * * @param x * x coordinate * @param y * y coordinate * @return block at x, y; null if there is no block there */ public Tetromino getBlock(int x, int y) { if (!isWithinBounds(x, y)) { throw new IndexOutOfBoundsException( String.format( "Point (%s, %s) is not within bounds: x should be between %s and %s, y between %s and %s.", Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(0), Integer.valueOf(width), Integer.valueOf(0), Integer.valueOf(getHeight()))); } return this.grid.get(toGridIndex(x, y)); } /** * Translates the given coordinates to an index in the grid. * * @param x x coordinate * @param y y coordinate * @return index in the grid */ private int toGridIndex(int x, int y) { return x + y * this.width; } /** * Translates the given coordinates to an index in the grid. * * @param point point * @return index in the grid */ public int toGridIndex(Point point) { return toGridIndex(point.getX(), point.getY()); } public boolean isTopped() { return vanishZoneContainsBlock() || containsBlock(getCurrentActiveBlockPoints()); } /** * Determines whether there is a block in the vanish zone. * * @return whether the grid's vanish zone contains at least one block */ private boolean vanishZoneContainsBlock() { boolean result = false; int height = getHeight(); for (int x = 0; !result && x != width; x++) { for (int y = height - VANISH_ZONE_HEIGHT; !result && y != height; y++) { result = result || getBlock(x, y) != null; } } return result; } /** * Indicates whether any of the given points in the grid contain a non-null block. * * Only the grid is inspected, not the current active block. * * @param points points to be checked * @return whether any of the points contain a block */ private boolean containsBlock(Set<Point> points) { boolean result = false; for (Point point: points) { result = result || getBlock(point.getX(), point.getY()) != null; } return result; } /** * Computes the points occupied by the currently active block. * * @return points occupied by the currently active block; empty set if there is no currently active block */ public Set<Point> getCurrentActiveBlockPoints() { return getBlockPoints(currentBlock, currentBlockOrientation, currentBlockLocation); } /** * Computes the points occupied by the given tetromino. * * @param tetromino tetromino * @param orientation orientation of the tetromino * @param location the tetromino's location * @return points occupied by the currently active block; empty set if there is no currently active block */ private Set<Point> getBlockPoints(Tetromino tetromino, Orientation orientation, Point location) { Set<Point> result; if (tetromino == null) { result = Collections.emptySet(); } else { result = translate(tetromino.getPoints(orientation), location.getX(), location.getY()); } return result; } /** * Computes the points occupied by the currently active block's ghost. * * @return points occupied by the currently active block; empty set if there is no currently active block */ public Set<Point> getGhostPoints() { return getBlockPoints(currentBlock, currentBlockOrientation, getGhostLocation()); } public boolean canMoveLeft() { return canMove(-1, 0); } public boolean canMoveRight() { return canMove(1, 0); } public boolean canMoveDown() { return canMove(0, -1); } private boolean canMove(int deltaX, int deltaY) { if (currentBlock == null) { throw new IllegalStateException("no active block"); } Set<Point> newPosition = translate(getCurrentActiveBlockPoints(), deltaX, deltaY); return isWithinBounds(newPosition) && !containsBlock(newPosition); } /** * Translates all points with the given delta. * * @param points points to be translated * @param deltaX amount to be added to x values * @param deltaY amount to be added to y values * @return */ private Set<Point> translate(Set<Point> points, int deltaX, int deltaY) { Set<Point> result = new HashSet<>(points.size()); for (Point point: points) { result.add(point.translate(deltaX, deltaY)); } return result; } /** * Determines whether the given point is within the bounds of the grid. * * @param x x coordinate * @param y y coordinate * @return whether the point is within bounds */ private boolean isWithinBounds(int x, int y) { boolean result = 0 <= x; result = result && x < width; result = result && 0 <= y; result = result && y < getHeight(); return result; } /** * Determines whether the given points are all within the bounds of the grid. * * @param points points * @return whether all points are within bounds */ private boolean isWithinBounds(Set<Point> points) { boolean result = true; for (Point point: points) { result = result && isWithinBounds(point.getX(), point.getY()); } return result; } /** * Indicates whether the active block is currently within bounds. Note that if this method returns false, this is * actually not a valid game state! * * @return whether the current block is within bounds. */ public boolean isCurrentBlockWithinBounds() { return isWithinBounds(getCurrentActiveBlockPoints()); } /** * Gives the location of the ghost, or null if there is no currently selected block. * * The ghost location is the location where the block would end up if it were dropped straight down from its current * position. * * @return ghost location */ public Point getGhostLocation() { Point result; if (currentBlock != null) { int deltaY = 0; while (canMove(0, deltaY - 1)) { deltaY = deltaY - 1; } result = new Point(currentBlockLocation.getX(), currentBlockLocation.getY() + deltaY); } else { result = null; } return result; } /** * Computes if the line is filled with (non-null) tetrominoes. * * @param y line number * @return whether the given line is filled */ public boolean isFullLine(int y) { boolean filled = true; int x = 0; while (filled && x != width) { filled = getBlock(x, y) != null; x++; } return filled; } /** * Creates an ascii representation of the grid. * * @return string representation of the grid */ private String gridToAscii() { StringBuilder result = new StringBuilder(); Set<Point> currentBlockPoints = getCurrentActiveBlockPoints(); Set<Point> ghostPoints = getGhostPoints(); for (int y = getHeight() - 1; y != -1; y result.append('|'); for (int x = 0; x != width; x++) { if (currentBlockPoints.contains(new Point(x, y))) { result.append(currentBlock); } else if (ghostPoints.contains(new Point(x, y))) { result.append('_'); } else { Tetromino block = getBlock(x, y); if (block == null) { result.append(' '); } else { result.append(block); } } } result.append("|\n"); } result.append('+'); for (int i = 0; i != width; i++) { result.append('-'); } result.append("+"); return result.toString(); } /** * {@inheritDoc} * * Note that this implementation contains newlines. */ @Override public String toString() { return "GameState (width=" + width + ", currentBlock=" + currentBlock + ", currentBlockLocation=" + currentBlockLocation + ", currentBlockOrientation = " + currentBlockOrientation + ", nextBlock=" + nextBlock + ", inputStateHistory=" + inputStateHistory + ", blockCounter = " + blockCounter + ", lines = " + lines + ", numFramesUntilLinesDisappear = " + numFramesUntilLinesDisappear + ", grid=\n" + gridToAscii() + ")"; } }
package to.etc.domui.injector; import org.eclipse.jdt.annotation.NonNull; import to.etc.domui.component.meta.PropertyMetaModel; import to.etc.domui.converter.CompoundKeyConverter; import to.etc.domui.dom.html.UrlPage; import to.etc.domui.state.IPageParameters; import to.etc.util.PropertyInfo; import to.etc.webapp.query.QDataContext; import to.etc.webapp.query.QNotFoundException; import java.util.Map; public class UrlFindEntityByPkInjector extends PropertyInjector { final private String m_name; final private boolean m_mandatory; final private Class< ? > m_entityClass; private final PropertyMetaModel<?> m_pkMetaPmm; public UrlFindEntityByPkInjector(PropertyInfo info, final String name, final boolean mandatory, final Class<?> enityClass, PropertyMetaModel<?> pkMetaPmm) { super(info); m_name = name; m_mandatory = mandatory; m_entityClass = enityClass; m_pkMetaPmm = pkMetaPmm; } protected String getParameterName() { return m_name; } protected boolean isMandatory() { return m_mandatory; } protected String getParameterValue(UrlPage page, IPageParameters papa) throws Exception { //-- 1. Get the URL parameter's value. String pv = papa.getString(m_name, null); if(pv == null) { if(m_mandatory) throw new IllegalArgumentException("The page " + page.getClass() + " REQUIRES the URL parameter " + m_name); return null; } return pv; } /** * Create a new instance. */ protected Object createNew(final UrlPage page) { try { return m_entityClass.newInstance(); } catch(Exception x) { throw new RuntimeException("Cannot create an instance of entity class '" + m_entityClass + "' for URL parameter=" + m_name + " of page=" + page.getClass() + ": " + x, x); } } /** * Returns T if the request is to create a new instance. */ protected boolean isNew(final UrlPage page, final IPageParameters papa, String value) throws Exception { return "NEW".equals(value); } protected Object getKeyInstance(QDataContext dc, final UrlPage page, String pkValue) throws Exception { // if the parametervalue has no value and the type of the key is Number, we treet it like no parameter was filled in // the mandatorycheck will be done some later if(Number.class.isAssignableFrom(m_pkMetaPmm.getActualType()) && pkValue != null && pkValue.length() == 0) return null; //-- Convert the URL's value to the TYPE of the primary key, using URL converters. Object pk; try { pk = CompoundKeyConverter.INSTANCE.unmarshal(dc, m_pkMetaPmm.getActualType(), pkValue); } catch(Exception x) { throw new RuntimeException("URL parameter value='" + pkValue + "' cannot be converted to a PK for '" + m_entityClass + "'" + "\n- error: " + x.toString() + "\n- parameter " + m_name + "\n- page " + page.getClass()); } if(pk == null) throw new RuntimeException("URL parameter value='" + pkValue + "' converted to Null primary key value for entity class '" + m_entityClass + "' for URL parameter=" + m_name + " of page=" + page.getClass()); return pk; } @Override public void inject(@NonNull final UrlPage page, @NonNull final IPageParameters papa, Map<String, Object> attributeMap) throws Exception { //-- 1. Get the URL parameter's value. String pv = getParameterValue(page, papa); if(pv == null) return; //-- 2. Handle the constant 'NEW'. Object value; if(isNew(page, papa, pv)) { value = createNew(page); } else { QDataContext dc = page.getSharedContext(); Object pk = getKeyInstance(dc, page, pv); if(pk == null) { if(m_mandatory) { throw new QNotFoundException(m_entityClass, pk); } return; } else { value = dc.find(m_entityClass, pk); if(value == null && m_mandatory) { throw new QNotFoundException(m_entityClass, pk); } } } setValue(page, value); } }
package org.mwc.cmap.xyplot.views; import java.awt.Color; import java.awt.Frame; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Ellipse2D; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import MWC.GUI.Editable; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.Shapes.LineShape; import MWC.GenericData.HiResDate; import MWC.GenericData.Watchable; import MWC.GenericData.WatchableList; public class CrossSectionViewer { private List<ISelectionChangedListener> _listeners = new ArrayList<ISelectionChangedListener>(); private List<PropertyChangeListener> _propListeners = new ArrayList<PropertyChangeListener>(); /** * the Swing control we insert the plot into */ private Frame _chartFrame; private JFreeChart _chart; private XYLineAndShapeRenderer _renderer = new XYLineAndShapeRenderer(); //TODO: get the units private ILocationCalculator _calc = new LocationCalculator(); private XYDataset _dataset; /** * the chart marker */ private static final Shape circle = new Ellipse2D.Double(-3, -3, 6, 6); protected CrossSectionViewer(final Composite parent) { //we need an SWT.EMBEDDED object to act as a holder final Composite holder = new Composite(parent, SWT.EMBEDDED); holder.setLayoutData(new GridData(GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL)); // now we need a Swing object to put our chart into _chartFrame = SWT_AWT.new_Frame(holder); //TODO: restore Previous Plot? _chart = ChartFactory.createXYLineChart ("Cross Section", // Title "Distances along the line", // X-Axis label "depth/elevation", // Y-Axis label _dataset, // Dataset, PlotOrientation.HORIZONTAL, true, // Show legend, true, //tooltips true //urs ); _chart.getXYPlot().setRenderer(_renderer); final ChartPanel jfreeChartPanel = new ChartPanel(_chart); _chartFrame.add(jfreeChartPanel); } public void fillPlot(final Layers theLayers, final LineShape line) { if (theLayers == null || line == null) return; walkThrough(theLayers, line); _chart.getXYPlot().setDataset(_dataset); printDataset(_dataset); } private void setDiscreteRenderer(Color paint) { _renderer.setSeriesShape(0, circle); _renderer.setSeriesPaint(0, paint); // _renderer.setSeriesPaint(0, line); _renderer.setUseFillPaint(true); _renderer.setSeriesShapesFilled(0, true); _renderer.setSeriesShapesVisible(0, true); _renderer.setUseOutlinePaint(true); //_renderer.setSeriesOutlinePaint(0, line); } private void setSnailRenderer() { } private void printDataset(XYDataset xydataset) { Comparable comparable; int indexOf; for (int i = 0; i < xydataset.getSeriesCount(); i++) { comparable = xydataset.getSeriesKey(i); indexOf = xydataset.indexOf(comparable); for (int j = 0; j < xydataset.getItemCount(indexOf); j++) { double x = xydataset.getXValue(indexOf, j); double y = xydataset.getYValue(indexOf, j); System.out.println(x + " ; " + y); } } } public void addSelectionChangedListener(final ISelectionChangedListener listener) { if (! _listeners.contains(listener)) _listeners.add(listener); } public void removeSelectionChangedListener( ISelectionChangedListener listener) { _listeners.remove(listener); } public void addPropertyChangedListener(final PropertyChangeListener listener) { if (! _propListeners.contains(listener)) _propListeners.add(listener); } public void removePropertyChangedListener( final PropertyChangeListener listener) { _propListeners.remove(listener); } private void walkThrough(final Object root, final LineShape line) { Enumeration<Editable> numer; if (root instanceof Layer) numer = ((Layer) root).elements(); else if (root instanceof Layers) numer = ((Layers) root).elements(); else return; while(numer.hasMoreElements()) { final Editable next = numer.nextElement(); if (next instanceof WatchableList) { final WatchableList wlist = (WatchableList) next; final HiResDate now = new HiResDate(); //TODO: check for Snail period final boolean is_snail = false; if (is_snail) { //TODO: get the snail period final HiResDate snail_period = new HiResDate(now.getDate().getTime() - 5); final long diff = now.getDate().getTime() - snail_period.getDate().getTime(); final HiResDate start_date = new HiResDate(diff); final Collection<Editable> wbs = wlist.getItemsBetween(start_date, now); final Iterator<Editable> itr = wbs.iterator(); //TODO: set the series name final XYSeries series = new XYSeries("Watchables between [now - snail_period; now]"); while (itr.hasNext()) { final Editable ed = itr.next(); if (ed instanceof Watchable) { final Double x_coord = new Double(_calc.getDistance(line, (Watchable) ed)); final Double y_coord = new Double(((Watchable) ed).getDepth()); series.add(x_coord, y_coord); } _dataset = new XYSeriesCollection(series); } } else { final Watchable[] wbs = wlist.getNearestTo(now); //TODO: set the series name final XYSeries series = new XYSeries("Watchables neares to Now"); for(Watchable wb: wbs) { final Double x_coord = new Double(_calc.getDistance(line, wb)); final Double y_coord = new Double(wb.getDepth()); series.add(x_coord, y_coord); } //TODO: remove hard-coded values series.add(0.0350068580566741, 0.0); _dataset = new XYSeriesCollection(series); setDiscreteRenderer(wlist.getColor()); } } if (!(next instanceof WatchableList)) walkThrough(next, line); } } private final class MyRenderer extends XYLineAndShapeRenderer { Color _color; MyRenderer(boolean lines, boolean shapes, Color color) { super(lines, shapes); _color = color; } @Override public Paint getItemFillPaint(int row, int column) { return _color; } } }
package org.tigris.subversion.subclipse.ui.subscriber; import java.text.DateFormat; import java.util.Date; import org.eclipse.team.core.synchronize.SyncInfo; import org.eclipse.team.core.synchronize.SyncInfoTree; import org.eclipse.team.core.variants.IResourceVariant; import org.eclipse.team.internal.core.subscribers.ChangeSet; import org.eclipse.team.internal.core.subscribers.CheckedInChangeSet; import org.eclipse.team.internal.ui.synchronize.SyncInfoSetChangeSetCollector; import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration; import org.tigris.subversion.subclipse.core.ISVNRemoteResource; import org.tigris.subversion.subclipse.core.SVNException; import org.tigris.subversion.subclipse.core.resources.RemoteResourceStatus; import org.tigris.subversion.subclipse.core.sync.SVNStatusSyncInfo; import org.tigris.subversion.subclipse.ui.Policy; import org.tigris.subversion.subclipse.ui.SVNUIPlugin; import org.tigris.subversion.svnclientadapter.ISVNClientAdapter; import org.tigris.subversion.svnclientadapter.ISVNLogMessage; import org.tigris.subversion.svnclientadapter.SVNClientException; import org.tigris.subversion.svnclientadapter.SVNRevision; import org.tigris.subversion.svnclientadapter.SVNUrl; public class SVNChangeSetCollector extends SyncInfoSetChangeSetCollector { /** * Change set used to store incoming changes in */ public class SVNCheckedInChangeSet extends CheckedInChangeSet { private long revision; private String author; private Date date; private String comment; /** * Create a checked in change set from the given syncinfo * @param info syncinfo to create change set from */ public SVNCheckedInChangeSet(SyncInfo info) { this(new SyncInfo[] { info }); } /** * Create a checked in change set from the given syncinfos * @param infos syncinfos to create change set from */ public SVNCheckedInChangeSet(SyncInfo[] infos) { super(); add(infos); initData(); String formattedDate = DateFormat.getInstance().format(date); setName(revision + " [" + author + "] (" + formattedDate + ") " + comment); } /* * (non-Javadoc) * @see org.eclipse.team.internal.core.subscribers.CheckedInChangeSet#getAuthor() */ public String getAuthor() { return author; } /** * Set the author of the change set */ public void setAuthor(String author) { this.author = author; } /* * (non-Javadoc) * @see org.eclipse.team.internal.core.subscribers.CheckedInChangeSet#getDate() */ public Date getDate() { return date; } /** * Sets the date of the change set */ public void setDate(Date date) { this.date = date; } /* * (non-Javadoc) * @see org.eclipse.team.internal.core.subscribers.ChangeSet#getComment() */ public String getComment() { return comment; } /** * Sets the comment of the change set * @param comment */ public void setComment(String comment) { this.comment = comment; } /** * Returns the revision of this checked in change set * @return revision of the change set */ public long getRevision() { return revision; } /** * Initialize the data of this checked in change set */ private void initData() { revision = SVNRevision.SVN_INVALID_REVNUM; SyncInfoTree syncInfoTree = getSyncInfoSet(); SyncInfo[] syncInfos = syncInfoTree.getSyncInfos(); if (syncInfos.length > 0) { SyncInfo syncInfo = syncInfos[0]; if (syncInfo instanceof SVNStatusSyncInfo) { SVNStatusSyncInfo svnSyncInfo = (SVNStatusSyncInfo)syncInfo; RemoteResourceStatus remoteResourceStatus = svnSyncInfo.getRemoteResourceStatus(); revision = remoteResourceStatus.getLastChangedRevision().getNumber(); author = remoteResourceStatus.getLastCommitAuthor(); if ((author == null) || (author.length() == 0)) { author = Policy.bind("SynchronizeView.noAuthor"); //$NON-NLS-1$ } date = remoteResourceStatus.getLastChangedDate(); comment = fetchComment(svnSyncInfo); } } } /** * Fetch the comment of the given SyncInfo * @param info info to get comment for * @return the comment */ private String fetchComment(SVNStatusSyncInfo info) { String fetchedComment = Policy.bind("SynchronizeView.standardIncomingChangeSetComment"); // $NON-NLS-1$ IResourceVariant remoteResource = info.getRemote(); if (remoteResource instanceof ISVNRemoteResource) { ISVNRemoteResource svnRemoteResource = (ISVNRemoteResource)remoteResource; try { ISVNClientAdapter client = svnRemoteResource.getRepository().getSVNClient(); SVNUrl url = svnRemoteResource.getRepository().getRepositoryRoot(); SVNRevision rev = svnRemoteResource.getLastChangedRevision(); ISVNLogMessage[] logMessages = client.getLogMessages(url, rev, rev, false); if (logMessages.length != 0) { String logComment = logMessages[0].getMessage(); if (logComment.trim().length() != 0) { fetchedComment = flattenComment(logComment); } else { fetchedComment = ""; } } } catch (SVNException e1) { SVNUIPlugin.log(e1); } catch (SVNClientException e) { SVNUIPlugin.log(SVNException.wrapException(e)); } } return fetchedComment; } } /** * Constructs a new SVNChangeSetCollector used to collect incoming * change sets */ public SVNChangeSetCollector(ISynchronizePageConfiguration configuration) { super(configuration); } /* * (non-Javadoc) * @see org.eclipse.team.internal.ui.synchronize.SyncInfoSetChangeSetCollector#add(org.eclipse.team.core.synchronize.SyncInfo[]) */ protected void add(SyncInfo[] infos) { for (int i=0; i<infos.length; i++) { SyncInfo syncInfo = infos[i]; if (syncInfo instanceof SVNStatusSyncInfo) { SVNStatusSyncInfo svnSyncInfo = (SVNStatusSyncInfo)syncInfo; RemoteResourceStatus resourceStatus = svnSyncInfo.getRemoteResourceStatus(); boolean added = false; ChangeSet[] changeSets = getSets(); for (int j=0; j<changeSets.length; j++) { ChangeSet changeSet = changeSets[j]; if (changeSet instanceof SVNCheckedInChangeSet) { SVNCheckedInChangeSet svnChangeSet = (SVNCheckedInChangeSet)changeSet; if (svnChangeSet.getRevision() == resourceStatus.getLastChangedRevision().getNumber()) { svnChangeSet.add(svnSyncInfo); added = true; break; } } } if (!added) { add(new SVNCheckedInChangeSet(svnSyncInfo)); } } } } /** * Flatten the given string so it contains no more line breaks * @param string String to strip linebreaks from * @return the string without any line breaks in it */ private String flattenComment(String string) { StringBuffer buffer = new StringBuffer(string.length() + 20); boolean skipAdjacentLineSeparator = true; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\r' || c == '\n') { if (!skipAdjacentLineSeparator) buffer.append(Policy.bind("separator")); //$NON-NLS-1$ skipAdjacentLineSeparator = true; } else { buffer.append(c); skipAdjacentLineSeparator = false; } } return buffer.toString(); } /* * (non-Javadoc) * @see org.eclipse.team.internal.core.subscribers.ChangeSetManager#initializeSets() */ protected void initializeSets() { // Nothing to initialize } }
package edu.cornell.mannlib.vitro.webapp.filestorage; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatementImpl; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.InsertException; import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileAlreadyExistsException; import edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorage; import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo; import edu.cornell.mannlib.vitro.webapp.filestorage.model.ImageInfo; /** * A helper object to handle the mundane details of dealing with uploaded files * in the model. */ public class UploadedFileHelper { private static final Log log = LogFactory.getLog(UploadedFileHelper.class); private final FileStorage fileStorage; private final WebappDaoFactory wadf; private final IndividualDao individualDao; private final DataPropertyStatementDao dataPropertyStatementDao; private final ObjectPropertyStatementDao objectPropertyStatementDao; public UploadedFileHelper(FileStorage fileStorage, WebappDaoFactory wadf) { this.fileStorage = fileStorage; this.wadf = wadf; this.individualDao = wadf.getIndividualDao(); this.dataPropertyStatementDao = wadf.getDataPropertyStatementDao(); this.objectPropertyStatementDao = wadf.getObjectPropertyStatementDao(); } /** * We have a filename, a mimetype, and some content. Create a file in the * file storage system and in the model. * * @return information about the newly created file. */ public FileInfo createFile(String filename, String mimeType, InputStream inputStream) throws FileAlreadyExistsException, IOException { if (filename == null) { throw new NullPointerException("filename may not be null."); } if (mimeType == null) { throw new NullPointerException("mimeType may not be null."); } if (inputStream == null) { throw new NullPointerException("inputStream may not be null."); } // Create the file individuals in the model Individual byteStream = createByteStreamIndividual(filename); String bytestreamUri = byteStream.getURI(); String aliasUrl = byteStream.getDataValue(VitroVocabulary.FS_ALIAS_URL); Individual file = createFileIndividual(mimeType, filename, byteStream); String fileUri = file.getURI(); // Store the file in the FileStorage system. fileStorage.createFile(bytestreamUri, filename, inputStream); // And wrap it all up in a tidy little package. FileInfo.Builder builder = new FileInfo.Builder(); builder.setFilename(filename); builder.setMimeType(mimeType); builder.setUri(fileUri); builder.setBytestreamUri(bytestreamUri); builder.setBytestreamAliasUrl(aliasUrl); return builder.build(); } /** * Record this image file and thumbnail on this entity. */ public void setImagesOnEntity(String entityUri, FileInfo mainInfo, FileInfo thumbInfo) { if (entityUri == null) { throw new NullPointerException("entityUri may not be null."); } if (mainInfo == null) { throw new NullPointerException("mainInfo may not be null."); } if (thumbInfo == null) { throw new NullPointerException("thumbInfo may not be null."); } Individual entity = individualDao.getIndividualByURI(entityUri); if (entity == null) { throw new NullPointerException("No entity found for URI '" + entityUri + "'."); } // Add the thumbnail file to the main image file. objectPropertyStatementDao .insertNewObjectPropertyStatement(new ObjectPropertyStatementImpl( mainInfo.getUri(), VitroVocabulary.FS_THUMBNAIL_IMAGE, thumbInfo.getUri())); // Add the main image file to the entity. entity.setMainImageUri(mainInfo.getUri()); individualDao.updateIndividual(entity); log.debug("Set images on '" + entity.getURI() + "': main=" + mainInfo + ", thumb=" + thumbInfo); } /** * If this Individual has an image, remove it and the thumbnail. If the * image file and/or the thumbnail file have no other references, delete * them. * * Note: after this operation, entity is stale. */ public void removeMainImage(Individual entity) { ImageInfo imageInfo = ImageInfo.instanceFromEntityUri(wadf, entity); if (imageInfo == null) { log.debug("No image to remove from '" + entity.getURI() + "'"); return; } // Remove the main image from the entity. entity.setMainImageUri(null); individualDao.updateIndividual(entity); // Remove the thumbnail from the main image. ObjectPropertyStatement stmt = new ObjectPropertyStatementImpl( imageInfo.getMainImage().getUri(), VitroVocabulary.FS_THUMBNAIL_IMAGE, imageInfo.getThumbnail() .getUri()); objectPropertyStatementDao.deleteObjectPropertyStatement(stmt); // If nobody else is using them, get rid of then. deleteIfNotReferenced(imageInfo.getMainImage()); deleteIfNotReferenced(imageInfo.getThumbnail()); } /** * Create a bytestream individual in the model. The only property is the * alias URL */ private Individual createByteStreamIndividual(String filename) { Individual byteStream = new IndividualImpl(); byteStream.setVClassURI(VitroVocabulary.FS_BYTESTREAM_CLASS); String uri = null; try { uri = individualDao.insertNewIndividual(byteStream); } catch (InsertException e) { throw new IllegalStateException( "Failed to create the bytestream individual.", e); } dataPropertyStatementDao .insertNewDataPropertyStatement(new DataPropertyStatementImpl( uri, VitroVocabulary.FS_ALIAS_URL, FileServingHelper .getBytestreamAliasUrl(uri, filename))); return individualDao.getIndividualByURI(uri); } /** * Create a file surrogate individual in the model. It has data properties * for filename and mimeType. It also has a link to its bytestream * Individual. */ private Individual createFileIndividual(String mimeType, String filename, Individual byteStream) { Individual file = new IndividualImpl(); file.setVClassURI(VitroVocabulary.FS_FILE_CLASS); String uri = null; try { uri = individualDao.insertNewIndividual(file); } catch (InsertException e) { throw new IllegalStateException( "Failed to create the file individual.", e); } dataPropertyStatementDao .insertNewDataPropertyStatement(new DataPropertyStatementImpl( uri, VitroVocabulary.FS_FILENAME, filename)); dataPropertyStatementDao .insertNewDataPropertyStatement(new DataPropertyStatementImpl( uri, VitroVocabulary.FS_MIME_TYPE, mimeType)); objectPropertyStatementDao .insertNewObjectPropertyStatement(new ObjectPropertyStatementImpl( uri, VitroVocabulary.FS_DOWNLOAD_LOCATION, byteStream .getURI())); return individualDao.getIndividualByURI(uri); } /** * If nobody is using this file any more, delete its bytestream from the * file system, and delete both the surrogate and the bytestream from the * model. */ private void deleteIfNotReferenced(FileInfo file) { if (!isFileReferenced(file.getUri())) { try { fileStorage.deleteFile(file.getBytestreamUri()); individualDao.deleteIndividual(file.getBytestreamUri()); individualDao.deleteIndividual(file.getUri()); } catch (IOException e) { throw new IllegalStateException("Can't delete the file: '" + file.getBytestreamUri(), e); } } } /** * Are there any ObjectPropertyStatements in the model whose object is this * file surrogate? */ private boolean isFileReferenced(String surrogateUri) { if (surrogateUri == null) { return false; } ObjectPropertyStatement opStmt = new ObjectPropertyStatementImpl(null, null, surrogateUri); List<ObjectPropertyStatement> stmts = objectPropertyStatementDao .getObjectPropertyStatements(opStmt); if (log.isDebugEnabled()) { log.debug(stmts.size() + " statements referencing '" + surrogateUri + "'"); for (ObjectPropertyStatement stmt : stmts) { log.debug("'" + stmt.getSubjectURI() + "' + stmt.getPropertyURI() + "' + stmt.getObjectURI() + "'"); } } return !stmts.isEmpty(); } }
package edu.cornell.mannlib.vitro.webapp.search.lucene; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.Term; import org.joda.time.DateTime; import com.hp.hpl.jena.vocabulary.OWL; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.IndividualImpl; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.VClass; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.search.IndexingException; import edu.cornell.mannlib.vitro.webapp.search.beans.IndividualProhibitedFromSearch; import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; import edu.cornell.mannlib.vitro.webapp.search.docbuilder.Obj2DocIface; /** * This class expect that Entities passed to it will have * a VClass object and a list of keywords. The entity should * be as full as possible. */ public class Entity2LuceneDoc implements Obj2DocIface{ /** These are the terms for the lucene index */ public static class VitroLuceneTermNames{ /** Id of entity, vclass or tab */ public static String URI = "URI"; /** lucene document id */ public static String DOCID = "DocId"; /** java class of the object that the Doc represents. */ public static String JCLASS = "JCLASS"; /** rdf:type */ public static String RDFTYPE = "type"; /** rdf:type */ public static String CLASSGROUP_URI = "classgroup"; /** Modtime from db */ public static String MODTIME = "modTime"; /** Name of entity, tab or vclass */ public static String NAME = "name"; /** rdfs:label unanalyzed */ public static String NAMELOWERCASE = "nameunanalyzed" ; /** Name of entity, unstemmed */ public static String NAMEUNSTEMMED = "nameunstemmed"; /** Unaltered name of individual, un-lowercased, un-stemmed, un-tokenized" */ public static String NAMERAW = "nameraw"; /** portal ( 2 ^ portalId ) */ public static String PORTAL = "portal"; /** time of index in msec since epoc */ public static String INDEXEDTIME= "indexedTime"; /** timekey of entity in yyyymmddhhmm */ public static String TIMEKEY="TIMEKEY"; /** time of sunset/end of entity in yyyymmddhhmm */ public static String SUNSET="SUNSET"; /** time of sunrise/start of entity in yyyymmddhhmm */ public static String SUNRISE="SUNRISE"; /** entity's moniker */ public static String MONIKER="moniker"; /** text for 'full text' search, this is stemmed */ public static String ALLTEXT = "ALLTEXT"; /** text for 'full text' search, this is unstemmed for * use with wildcards and prefix queries */ public static String ALLTEXTUNSTEMMED = "ALLTEXTUNSTEMMED"; /** keywords */ public static final String KEYWORDS = "KEYWORDS"; /** Does the individual have a thumbnail image? 1=yes 0=no */ public static final String THUMBNAIL = "THUMBNAIL"; /** Should individual be included in full text search results? 1=yes 0=no */ public static final String PROHIBITED_FROM_TEXT_RESULTS = "PROHIBITED_FROM_TEXT_RESULTS"; } private static final Log log = LogFactory.getLog(Entity2LuceneDoc.class.getName()); public static String earliestTime = "16000101"; public static String latestTime = "30000101"; /** a way to get to the term names for the lucene index */ public static VitroLuceneTermNames term = new VitroLuceneTermNames(); private static String entClassName = Individual.class.getName(); private ProhibitedFromSearch classesProhibitedFromSearch; private IndividualProhibitedFromSearch individualProhibited; public Entity2LuceneDoc( ProhibitedFromSearch classesProhibitedFromSearch, IndividualProhibitedFromSearch individualProhibited){ this.classesProhibitedFromSearch = classesProhibitedFromSearch; this.individualProhibited = individualProhibited; } public boolean canTranslate(Object obj) { return (obj != null && obj instanceof Individual); } @SuppressWarnings("static-access") public Object translate(Object obj) throws IndexingException { if(!( obj instanceof Individual)) return null; Individual ent = (Individual)obj; String value; Document doc = new Document(); String classPublicNames = ""; //DocId String id = ent.getURI(); log.debug("translating " + id); if( id == null ){ log.debug("cannot add individuals without URIs to lucene index"); return null; }else if( id.startsWith( VitroVocabulary.vitroURI ) || id.startsWith( VitroVocabulary.VITRO_PUBLIC ) || id.startsWith( VitroVocabulary.PSEUDO_BNODE_NS) || id.startsWith( OWL.NS ) ){ log.debug("not indxing because of namespace:" + id ); return null; } //filter out class groups, owl:ObjectProperties etc. if( individualProhibited.isIndividualProhibited( id ) ){ return null; } /* Types and ClassGroup */ boolean prohibited = false; List<VClass> vclasses = ent.getVClasses(false); for( VClass clz : vclasses){ if( clz.getURI() == null ){ continue; }else if( OWL.Thing.getURI().equals( clz.getURI()) ){ //index individuals of type owl:Thing, just don't add owl:Thing the type field in the index continue; } else if ( clz.getURI().startsWith( OWL.NS ) ){ log.debug("not indexing " + id + " because of type " + clz.getURI()); return null; }else{ if( !prohibited && classesProhibitedFromSearch.isClassProhibited(clz.getURI()) ) prohibited = true; if( clz.getSearchBoost() != null ) doc.setBoost( doc.getBoost() + clz.getSearchBoost() ); Field typeField = new Field (term.RDFTYPE, clz.getName(), Field.Store.YES, Field.Index.ANALYZED); //typeField.setBoost(2*FIELD_BOOST); doc.add( typeField); if( clz.getName() != null ) classPublicNames = classPublicNames + " " + clz.getName(); //Classgroup URI if( clz.getGroupURI() != null ){ Field classGroupField = new Field(term.CLASSGROUP_URI, clz.getGroupURI(), Field.Store.YES, Field.Index.ANALYZED); // classGroupField.setBoost(FIELD_BOOST); doc.add(classGroupField); } } } doc.add( new Field(term.PROHIBITED_FROM_TEXT_RESULTS, prohibited?"1":"0", Field.Store.NO,Field.Index.NOT_ANALYZED_NO_NORMS) ); /* lucene DOCID */ doc.add( new Field(term.DOCID, entClassName + id, Field.Store.YES, Field.Index.NOT_ANALYZED)); //vitro Id doc.add( new Field(term.URI, id, Field.Store.YES, Field.Index.NOT_ANALYZED)); //java class doc.add( new Field(term.JCLASS, entClassName, Field.Store.YES, Field.Index.NOT_ANALYZED)); //Entity Name if( ent.getRdfsLabel() != null ) value=ent.getRdfsLabel(); else{ //log.debug("Skipping individual without rdfs:label " + ent.getURI()); //return null; log.debug("Using local name for individual with rdfs:label " + ent.getURI()); value = ent.getLocalName(); } Field name =new Field(term.NAME, value, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); // name.setBoost( NAME_BOOST ); doc.add( name ); Field nameUn = new Field(term.NAMEUNSTEMMED, value, Field.Store.NO, Field.Index.ANALYZED); // nameUn.setBoost( NAME_BOOST ); doc.add( nameUn ); Field nameUnanalyzed = new Field(term.NAMELOWERCASE, value.toLowerCase(), Field.Store.YES, Field.Index.NOT_ANALYZED); doc.add( nameUnanalyzed ); doc.add( new Field(term.NAMERAW, value, Field.Store.YES, Field.Index.NOT_ANALYZED)); //Moniker if(ent.getMoniker() != null){ Field moniker = new Field(term.MONIKER, ent.getMoniker(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); // moniker.setBoost(MONIKER_BOOST); doc.add(moniker); } //boost for entity if( ent.getSearchBoost() != null && ent.getSearchBoost() != 0 ) doc.setBoost(ent.getSearchBoost()); //Modification time if( ent.getModTime() != null){ value = (new DateTime(ent.getModTime().getTime())) .toString(LuceneIndexer.MODTIME_DATE_FORMAT) ; } else { value= (new DateTime()).toString(LuceneIndexer.MODTIME_DATE_FORMAT) ; } doc.add( new Field(term.MODTIME, value , Field.Store.YES, Field.Index.NOT_ANALYZED)); /* timekey */ try{ value = null; if( ent.getTimekey() != null ){ value = (new DateTime(ent.getTimekey().getTime())).toString(LuceneIndexer.DATE_FORMAT); doc.add(new Field(term.TIMEKEY, value, Field.Store.YES, Field.Index.NOT_ANALYZED)); } }catch(Exception ex){ log.error("could not save timekey " + ex); } //time of index in millis past epoc Object anon[] = { new Long((new DateTime() ).getMillis()) }; doc.add( new Field(term.INDEXEDTIME, String.format( "%019d", anon ), Field.Store.YES, Field.Index.NOT_ANALYZED)); if( ! prohibited ){ //ALLTEXT, all of the 'full text' String t=null; value =""; value+= " "+( ((t=ent.getName()) == null)?"":t ); value+= " "+( ((t=ent.getAnchor()) == null)?"":t); value+= " "+ ( ((t=ent.getMoniker()) == null)?"":t ); value+= " "+ ( ((t=ent.getDescription()) == null)?"":t ); value+= " "+ ( ((t=ent.getBlurb()) == null)?"":t ); value+= " "+ getKeyterms(ent); value+= " " + classPublicNames; List<DataPropertyStatement> dataPropertyStatements = ent.getDataPropertyStatements(); if (dataPropertyStatements != null) { Iterator<DataPropertyStatement> dataPropertyStmtIter = dataPropertyStatements.iterator(); while (dataPropertyStmtIter.hasNext()) { DataPropertyStatement dataPropertyStmt = dataPropertyStmtIter.next(); value+= " "+ ( ((t=dataPropertyStmt.getData()) == null)?"":t ); } } List<ObjectPropertyStatement> objectPropertyStatements = ent.getObjectPropertyStatements(); if (objectPropertyStatements != null) { Iterator<ObjectPropertyStatement> objectPropertyStmtIter = objectPropertyStatements.iterator(); while (objectPropertyStmtIter.hasNext()) { ObjectPropertyStatement objectPropertyStmt = objectPropertyStmtIter.next(); if( "http://www.w3.org/2002/07/owl#differentFrom".equals(objectPropertyStmt.getPropertyURI()) ) continue; try { value+= " "+ ( ((t=objectPropertyStmt.getObject().getName()) == null)?"":t ); } catch (Exception e) { log.debug("could not index name of related object: " + e.getMessage()); } } } //stemmed terms doc.add( new Field(term.ALLTEXT, value , Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES)); //unstemmed terms doc.add( new Field(term.ALLTEXTUNSTEMMED, value, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES)); } //flagX and portal flags are no longer indexed. return doc; } @SuppressWarnings("static-access") public boolean canUnTranslate(Object result) { if( result != null && result instanceof Document){ Document hit = (Document) result; if( entClassName.equalsIgnoreCase(hit.get(term.JCLASS)) ){ return true; } } return false; } @SuppressWarnings("static-access") public Object unTranslate(Object result) { Individual ent = null; if( result != null && result instanceof Document){ Document hit = (Document) result; String id = hit.get(term.URI); ent = new IndividualImpl(); ent.setURI(id); } return ent; } @SuppressWarnings("static-access") public Object getIndexId(Object obj) { return new Term(term.DOCID, entClassName + ((Individual)obj).getURI() ) ; } private String getKeyterms(Individual ent){ /* bdc34: vitro:keywords are no longer being indexed */ return ""; } public ProhibitedFromSearch getClassesProhibitedFromSearch() { return classesProhibitedFromSearch; } public void setClassesProhibitedFromSearch( ProhibitedFromSearch classesProhibitedFromSearch) { this.classesProhibitedFromSearch = classesProhibitedFromSearch; } public static float NAME_BOOST = 3.0F; public static float MONIKER_BOOST = 2.0F; public static float FIELD_BOOST = 1.0F; }
package won.node.service.persistence; import java.lang.invoke.MethodHandles; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.EntityManager; import org.apache.jena.query.Dataset; import org.apache.jena.rdf.model.Model; import org.javasimon.SimonManager; import org.javasimon.Split; import org.javasimon.Stopwatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import won.node.service.nodeconfig.URIService; import won.protocol.exception.IllegalAtomContentException; import won.protocol.exception.IllegalAtomURIException; import won.protocol.exception.IllegalSocketModificationException; import won.protocol.exception.MissingMessagePropertyException; import won.protocol.exception.NoSuchAtomException; import won.protocol.exception.UriAlreadyInUseException; import won.protocol.exception.WonMessageProcessingException; import won.protocol.exception.WrongAddressingInformationException; import won.protocol.message.WonMessage; import won.protocol.message.WonMessageDirection; import won.protocol.message.WonMessageType; import won.protocol.message.WonMessageUtils; import won.protocol.model.Atom; import won.protocol.model.AtomMessageContainer; import won.protocol.model.AtomState; import won.protocol.model.ConnectionContainer; import won.protocol.model.ConnectionState; import won.protocol.model.DatasetHolder; import won.protocol.model.OwnerApplication; import won.protocol.model.Socket; import won.protocol.repository.AtomMessageContainerRepository; import won.protocol.repository.AtomRepository; import won.protocol.repository.ConnectionContainerRepository; import won.protocol.repository.MessageEventRepository; import won.protocol.repository.OwnerApplicationRepository; import won.protocol.repository.SocketRepository; import won.protocol.util.AtomModelWrapper; import won.protocol.util.RdfUtils; import won.protocol.vocabulary.WONMSG; @Component public class AtomService { private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Autowired AtomMessageContainerRepository atomMessageContainerRepository; @Autowired ConnectionContainerRepository connectionContainerRepository; @Autowired AtomRepository atomRepository; @Autowired SocketRepository socketRepository; @Autowired OwnerApplicationRepository ownerApplicationRepository; @Autowired MessageEventRepository messageEventRepository; @Autowired MessageService messageService; @Autowired URIService uriService; @Autowired ConnectionService connectionService; @Autowired EntityManager entityManager; public Optional<Atom> getAtomForUpdate(URI atomURI) { Optional<Atom> atom = atomRepository.findOneByAtomURIForUpdate(atomURI); entityManager.refresh(atom.get()); return atom; } public Optional<Atom> getAtom(URI atomURI) { return atomRepository.findOneByAtomURI(atomURI); } public Optional<Atom> lockAtom(URI atomURI) { Optional<Atom> atom = atomRepository.findOneByAtomURIForUpdate(atomURI); entityManager.refresh(atom.get()); return atom; } public Atom lockAtomRequired(URI atomURI) { return atomRepository.findOneByAtomURIForUpdate(atomURI).orElseThrow(() -> new NoSuchAtomException(atomURI)); } public Atom getAtomRequired(URI atomURI) { return getAtom(atomURI).orElseThrow(() -> new NoSuchAtomException(atomURI)); } public Optional<Atom> getAtomForMessage(WonMessage msg, WonMessageDirection direction) { URI socketURI = null; URI atomURI = null; if (msg.getMessageTypeRequired().isConnectionSpecificMessage()) { if (direction.isFromExternal()) { socketURI = msg.getRecipientSocketURI(); } else { socketURI = msg.getSenderSocketURI(); } if (socketURI == null) { return Optional.empty(); } atomURI = WonMessageUtils.stripFragment(socketURI); } else { atomURI = msg.getRecipientAtomURI(); } if (atomURI == null) { atomURI = msg.getSenderAtomURI(); } if (atomURI != null) { return getAtom(atomURI); } return Optional.empty(); } public Atom getAtomForMessageRequired(WonMessage msg, WonMessageDirection direction) { URI socketURI = null; URI atomURI = null; if (msg.getMessageTypeRequired().isConnectionSpecificMessage()) { if (direction.isFromExternal()) { socketURI = msg.getRecipientSocketURIRequired(); } else { socketURI = msg.getSenderSocketURIRequired(); } atomURI = WonMessageUtils.stripFragment(socketURI); } else { atomURI = msg.getRecipientAtomURI(); } if (atomURI == null) { atomURI = msg.getSenderAtomURI(); } if (atomURI != null) { return getAtomRequired(atomURI); } else { throw new WonMessageProcessingException("Could not obtain atom URI from messsage " + msg.getMessageURI()); } } public Atom createAtom(final WonMessage wonMessage) { wonMessage.getMessageType().requireType(WonMessageType.CREATE_ATOM); Dataset atomContent = wonMessage.getMessageContent(); List<WonMessage.AttachmentHolder> attachmentHolders = wonMessage.getAttachments(); // remove attachment and its signature from the atomContent removeAttachmentsFromAtomContent(atomContent, attachmentHolders); URI messageURI = wonMessage.getMessageURI(); final AtomModelWrapper atomModelWrapper = new AtomModelWrapper(atomContent); URI atomURI = getAtomURIAndCheck(atomModelWrapper); // rename the content graphs and signature graphs so they start with the atom // uri Collection<String> sockets = getSocketsAndCheck(atomModelWrapper, atomURI); Optional<String> defaultSocket = getDefaultSocketAndCheck(atomModelWrapper, sockets); Set<Socket> socketEntities = sockets.stream().map(socketUri -> { Optional<String> socketType = getSocketTypeAndCheck(atomModelWrapper, socketUri); Socket f = new Socket(); f.setAtomURI(atomURI); f.setSocketURI(URI.create(socketUri)); f.setTypeURI(URI.create(socketType.get())); if (defaultSocket.isPresent() && socketUri.equals(defaultSocket.get())) { f.setDefaultSocket(true); } return f; }).collect(Collectors.toSet()); checkResourcesInAtomContent(atomModelWrapper); // add everything to the atom model class and save it checkCanThisMessageCreateOrModifyThisAtom(wonMessage, atomURI); Atom atom = new Atom(); atom.setState(AtomState.ACTIVE); atom.setAtomURI(atomURI); // make a new wrapper because we just changed the underlying dataset atom.setWonNodeURI(URI.create(uriService.getResourceURIPrefix())); ConnectionContainer connectionContainer = new ConnectionContainer(atom); atom.setConnectionContainer(connectionContainer); AtomMessageContainer atomMessageContainer = atomMessageContainerRepository.findOneByParentUri(atomURI); if (atomMessageContainer == null) { atomMessageContainer = new AtomMessageContainer(atom, atom.getAtomURI()); } else { throw new UriAlreadyInUseException("Found an AtomMessageContainer for the atom we're about to create (" + atomURI + ") - aborting"); } atom.setMessageContainer(atomMessageContainer); // store the atom content atomModelWrapper.renameResourceWithPrefix(messageURI.toString(), atomURI.toString()); DatasetHolder datasetHolder = new DatasetHolder(atomURI, atomModelWrapper.getDataset()); // store attachments List<DatasetHolder> attachments = new ArrayList<>(attachmentHolders.size()); for (WonMessage.AttachmentHolder attachmentHolder : attachmentHolders) { datasetHolder = new DatasetHolder(attachmentHolder.getDestinationUri(), attachmentHolder.getAttachmentDataset()); attachments.add(datasetHolder); } atom.setDatatsetHolder(datasetHolder); atom.setAttachmentDatasetHolders(attachments); atom = atomRepository.save(atom); connectionContainerRepository.save(connectionContainer); socketEntities.forEach(socket -> socketRepository.save(socket)); return atom; } public Atom replaceAtom(final WonMessage wonMessage) throws NoSuchAtomException { Dataset atomContent = wonMessage.getMessageContent(); List<WonMessage.AttachmentHolder> attachmentHolders = wonMessage.getAttachments(); // remove attachment and its signature from the atomContent removeAttachmentsFromAtomContent(atomContent, attachmentHolders); final AtomModelWrapper atomModelWrapper = new AtomModelWrapper(atomContent); URI atomURI = getAtomURIAndCheck(atomModelWrapper); checkCanThisMessageCreateOrModifyThisAtom(wonMessage, atomURI); checkResourcesInAtomContent(atomModelWrapper); Collection<String> sockets = getSocketsAndCheck(atomModelWrapper, atomURI); getDefaultSocketAndCheck(atomModelWrapper, sockets); final Atom atom = getAtomRequired(atomURI); URI messageURI = wonMessage.getMessageURI(); // store the atom content DatasetHolder datasetHolder = atom.getDatatsetHolder(); // get the derived data, we don't change that here Dataset atomDataset = atom.getDatatsetHolder().getDataset(); Optional<Model> derivationModel = Optional .ofNullable(atomDataset.getNamedModel(atom.getAtomURI() + "#derivedData")); // replace attachments List<DatasetHolder> attachments = new ArrayList<>(attachmentHolders.size()); for (WonMessage.AttachmentHolder attachmentHolder : attachmentHolders) { datasetHolder = new DatasetHolder(attachmentHolder.getDestinationUri(), attachmentHolder.getAttachmentDataset()); attachments.add(datasetHolder); } // rename the content graphs and signature graphs so they start with the atom // uri // analyzed change in socket data atomModelWrapper.renameResourceWithPrefix(messageURI.toString(), atomURI.toString()); List<Socket> existingSockets = socketRepository.findByAtomURI(atomURI); Set<Socket> newSocketEntities = determineNewSockets(atomURI, existingSockets, atomModelWrapper); Set<Socket> removedSockets = determineRemovedSockets(atomURI, existingSockets, atomModelWrapper); Set<Socket> changedSockets = determineAndModifyChangedSockets(atomURI, existingSockets, atomModelWrapper); // close connections for changed or removed sockets removedSockets .stream() .filter(socket -> connectionService.existOpenConnections(atomURI, socket.getSocketURI())) .findFirst() .ifPresent(socket -> new IllegalSocketModificationException("Cannot remove socket " + socket.getSocketURI() + ": socket has connections in state " + ConnectionState.CONNECTED)); changedSockets .stream() .filter(socket -> connectionService.existOpenConnections(atomURI, socket.getSocketURI())) .findFirst() .ifPresent(socket -> new IllegalSocketModificationException("Cannot change socket " + socket.getSocketURI() + ": socket has connections in state " + ConnectionState.CONNECTED)); // add everything to the atom model class and save it socketRepository.save(newSocketEntities); socketRepository.save(changedSockets); socketRepository.delete(removedSockets); if (derivationModel.isPresent()) { atomContent.addNamedModel(atom.getAtomURI().toString() + "#derivedData", derivationModel.get()); } datasetHolder.setDataset(atomContent); atom.setDatatsetHolder(datasetHolder); atom.setAttachmentDatasetHolders(attachments); return atomRepository.save(atom); } private Set<Socket> determineNewSockets(URI atomURI, List<Socket> existingSockets, AtomModelWrapper atomModelWrapper) { Collection<String> sockets = atomModelWrapper.getSocketUris(); Optional<String> defaultSocket = atomModelWrapper.getDefaultSocket(); if (sockets.size() == 0) throw new IllegalAtomContentException("at least one property won:socket required "); // create new socket entities for the sockets not yet existing: Set<Socket> newSocketEntities = sockets.stream() .filter(socketUri -> !existingSockets.stream() .anyMatch(socket -> socket.getSocketURI().toString().equals(socketUri))) .map(socketUri -> { Optional<String> socketType = atomModelWrapper.getSocketType(socketUri); if (!socketType.isPresent()) { throw new IllegalAtomContentException("cannot determine type of socket " + socketUri); } Socket f = new Socket(); f.setAtomURI(atomURI); f.setSocketURI(URI.create(socketUri)); f.setTypeURI(URI.create(socketType.get())); if (defaultSocket.isPresent() && socketUri.equals(defaultSocket.get())) { f.setDefaultSocket(true); } return f; }).collect(Collectors.toSet()); return newSocketEntities; } private Set<Socket> determineRemovedSockets(URI atomURI, List<Socket> existingSockets, AtomModelWrapper atomModelWrapper) { Collection<String> sockets = atomModelWrapper.getSocketUris(); return existingSockets.stream().filter(socket -> !sockets.contains(socket.getSocketURI().toString())) .collect(Collectors.toSet()); } private Set<Socket> determineAndModifyChangedSockets(URI atomURI, List<Socket> existingSockets, AtomModelWrapper atomModelWrapper) { Collection<String> sockets = atomModelWrapper.getSocketUris(); Optional<URI> defaultSocket = atomModelWrapper.getDefaultSocket().map(f -> URI.create(f)); return existingSockets.stream().filter(socket -> { if (!sockets.contains(socket.getSocketURI().toString())) { // socket is removed, not changed return false; } boolean changed = false; boolean isNowDefaultSocket = defaultSocket.isPresent() && defaultSocket.get().equals(socket.getSocketURI()); if (isNowDefaultSocket != socket.isDefaultSocket()) { // socket's default socket property has changed changed = true; socket.setDefaultSocket(isNowDefaultSocket); } Optional<URI> newSocketType = atomModelWrapper.getSocketType(socket.getSocketURI().toString()) .map(f -> URI.create(f)); boolean typeChanged = newSocketType.isPresent() && !newSocketType.get().equals(socket.getTypeURI()); if (typeChanged) { // socket's type has changed socket.setTypeURI(newSocketType.get()); changed = true; } return changed; }).collect(Collectors.toSet()); } private void checkResourcesInAtomContent(AtomModelWrapper atomModelWrapper) { String atomURI = atomModelWrapper.getAtomUri(); final String illegalPrefix = atomURI + "/"; if (RdfUtils .toURIStream(atomModelWrapper.getDataset(), true) .anyMatch(uri -> uri.startsWith(illegalPrefix))) { throw new IllegalAtomContentException( "URIs in atom content cannot be a sub-paths of the atom URI (i.e., they cannot start with '" + illegalPrefix + "'). If you need URIs for resources in your content, use fragments " + "of the atom URI (i.e., URIs that start with '" + atomURI + " } } private void checkCanThisMessageCreateOrModifyThisAtom(final WonMessage wonMessage, URI atomURI) { if (!atomURI.equals(wonMessage.getSenderAtomURI())) throw new WrongAddressingInformationException("recipientAtomURI and AtomURI of the content are not equal", wonMessage.getMessageURI(), WONMSG.recipientAtom); if (!uriService.isAtomURI(atomURI)) { throw new IllegalAtomURIException("Atom URI " + atomURI + "does not match this node's prefix " + uriService.getAtomResourceURIPrefix()); } } private Optional<String> getSocketTypeAndCheck(final AtomModelWrapper atomModelWrapper, String socketUri) { Optional<String> socketType = atomModelWrapper.getSocketType(socketUri); if (!socketType.isPresent()) { throw new IllegalAtomContentException("Missing SocketDefinition for socket " + socketUri + ". Add a '[socket] won:socketDefinition [SocketDefinition]' triple!"); } return socketType; } private Optional<String> getDefaultSocketAndCheck(final AtomModelWrapper atomModelWrapper, Collection<String> sockets) { Optional<String> defaultSocket = atomModelWrapper.getDefaultSocket(); if (defaultSocket.isPresent() && !sockets.contains(defaultSocket.get())) { throw new IllegalAtomContentException( "DefaultSocket must be one of the sockets defined in the atom. This one is not: " + defaultSocket.get()); } return defaultSocket; } private Collection<String> getSocketsAndCheck(final AtomModelWrapper atomModelWrapper, URI atomURI) { Collection<String> sockets = atomModelWrapper.getSocketUris(); sockets.parallelStream().forEach(socketUri -> { if (!socketUri.toString().startsWith(atomURI.toString() + " throw new IllegalAtomContentException( "Socket URIs must be fragments of atom URIs (i.e. [socketURI] = [atomURI] + ' + "This rule is violated for atom '" + atomURI + "' and socket '" + socketUri + "'"); } getSocketTypeAndCheck(atomModelWrapper, socketUri); }); if (sockets.size() == 0) throw new IllegalAtomContentException("at least one property won:socket required "); return sockets; } private URI getAtomURIAndCheck(final AtomModelWrapper atomModelWrapper) { URI atomURI; String atomURIString = atomModelWrapper.getAtomUri(); if (atomURIString == null) { throw new IllegalAtomContentException("No '[subj] rdf:type won:Atom' triple found in atom content"); } try { atomURI = new URI(atomURIString); } catch (URISyntaxException e) { throw new IllegalAtomURIException("Not a valid atom URI: " + atomModelWrapper.getAtomUri()); } if (atomURI.getRawFragment() != null) { throw new IllegalAtomURIException( "Atom URI must not be a fragment URI (i.e., no trailing '#' + [fragment-id] allowed). This is not allowed: " + atomURI); } return atomURI; } public Atom authorizeOwnerApplicationForAtom(final String ownerApplicationID, Atom atom) { String stopwatchName = getClass().getName() + ".authorizeOwnerApplicationForAtom"; Stopwatch stopwatch = SimonManager.getStopwatch(stopwatchName + "_phase1"); Split split = stopwatch.start(); List<OwnerApplication> ownerApplications = ownerApplicationRepository .findByOwnerApplicationId(ownerApplicationID); split.stop(); stopwatch = SimonManager.getStopwatch(stopwatchName + "_phase2"); split = stopwatch.start(); if (ownerApplications.size() > 0) { logger.debug("owner application is already known"); OwnerApplication ownerApplication = ownerApplications.get(0); List<OwnerApplication> authorizedApplications = atom.getAuthorizedApplications(); if (authorizedApplications == null) { authorizedApplications = new ArrayList<OwnerApplication>(1); } authorizedApplications.add(ownerApplication); atom.setAuthorizedApplications(authorizedApplications); } else { logger.debug("owner application is new - creating"); List<OwnerApplication> ownerApplicationList = new ArrayList<>(1); OwnerApplication ownerApplication = new OwnerApplication(); ownerApplication.setOwnerApplicationId(ownerApplicationID); ownerApplicationRepository.save(ownerApplication); ownerApplicationList.add(ownerApplication); atom.setAuthorizedApplications(ownerApplicationList); logger.debug("setting OwnerApp ID: " + ownerApplicationList.get(0)); } split.stop(); stopwatch = SimonManager.getStopwatch(stopwatchName + "_phase3"); split = stopwatch.start(); atom = atomRepository.save(atom); split.stop(); return atom; } public void activate(WonMessage wonMessage) throws NoSuchAtomException { URI messageURI = wonMessage.getMessageURI(); URI recipientAtomURI = wonMessage.getRecipientAtomURI(); wonMessage.getMessageType().requireType(WonMessageType.ACTIVATE); activate(recipientAtomURI, messageURI); } public void activate(URI atomURI, URI messageURI) throws NoSuchAtomException { logger.debug("ACTIVATING atom. atomURI:{}", atomURI); Objects.requireNonNull(atomURI); Objects.requireNonNull(messageURI); Atom atom = getAtomRequired(atomURI); logger.debug("atom State: " + atom.getState()); atom.setState(AtomState.ACTIVE); atomRepository.save(atom); logger.debug("atom State: " + atom.getState()); } public void deactivate(WonMessage wonMessage) { wonMessage.getMessageType().requireType(WonMessageType.DEACTIVATE); URI recipientAtomURI = wonMessage.getRecipientAtomURI(); URI senderAtomURI = wonMessage.getSenderAtomURI(); URI messageURI = wonMessage.getMessageURI(); if (recipientAtomURI == null) { throw new MissingMessagePropertyException(URI.create(WONMSG.recipientAtom.toString())); } if (senderAtomURI == null) { throw new MissingMessagePropertyException(URI.create(WONMSG.senderAtom.toString())); } deactivate(recipientAtomURI, messageURI); } public void deactivate(URI atomURI, URI messageURI) { logger.debug("DEACTIVATING atom. atomURI:{}", atomURI); Objects.requireNonNull(atomURI); Objects.requireNonNull(messageURI); Optional<Atom> atom = getAtomForUpdate(atomURI); logger.debug("atom State: " + atom.get().getState()); atom.get().setState(AtomState.INACTIVE); atomRepository.save(atom.get()); logger.debug("atom State: " + atom.get().getState()); } public void atomMessageFromSystem(WonMessage wonMessage) { URI recipientAtomURI = wonMessage.getRecipientAtomURI(); URI senderAtomURI = wonMessage.getSenderAtomURI(); URI messageURI = wonMessage.getMessageURI(); if (recipientAtomURI == null) { throw new MissingMessagePropertyException(URI.create(WONMSG.recipientAtom.toString())); } if (senderAtomURI == null) { throw new MissingMessagePropertyException(URI.create(WONMSG.senderAtom.toString())); } if (!recipientAtomURI.equals(senderAtomURI)) { throw new WrongAddressingInformationException("SenderAtomUri and recipientAtomUri must be identical", URI.create(WONMSG.senderAtom.getURI()), URI.create(WONMSG.recipientAtom.getURI())); } } private void removeAttachmentsFromAtomContent(Dataset atomContent, List<WonMessage.AttachmentHolder> attachmentHolders) { for (WonMessage.AttachmentHolder attachmentHolder : attachmentHolders) { for (Iterator<String> it = attachmentHolder.getAttachmentDataset().listNames(); it.hasNext();) { String modelName = it.next(); atomContent.removeNamedModel(modelName); } } } }
package won.owner.web; import org.apache.jena.query.Dataset; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import won.owner.service.impl.URIService; import won.protocol.model.ConnectionState; import won.protocol.util.DefaultNeedModelWrapper; import won.protocol.util.linkeddata.LinkedDataSource; import won.utils.mail.WonMailSender; import java.io.StringWriter; import java.net.URI; import java.util.Properties; public class WonOwnerMailSender { private final Logger logger = LoggerFactory.getLogger(getClass()); private static final String OWNER_REMOTE_NEED_LINK = "/#!post/?postUri="; private static final String OWNER_CONNECTION_LINK = "/#!post/?postUri=%s&connectionUri=%s&connectionType=%s"; private static final String OWNER_LOCAL_NEED_LINK = "/#!post/?postUri="; private static final String SUBJECT_CONVERSATION_MESSAGE = "New message"; private static final String SUBJECT_CONNECT = "New conversation request"; private static final String SUBJECT_MATCH = "New match"; private static final String SUBJECT_CLOSE = "Conversation closed"; private static final String SUBJECT_SYSTEM_CLOSE = "Conversation closed by system"; private static final String SUBJECT_NEED_MESSAGE = "Notification from WoN node"; private static final String SUBJECT_SYSTEM_DEACTIVATE = "Posting deactivated by system"; private WonMailSender wonMailSender; @Autowired LinkedDataSource linkedDataSource; @Autowired private URIService uriService; private VelocityEngine velocityEngine; private Template conversationNotificationHtmlTemplate; private Template connectNotificationHtmlTemplate; private Template closeNotificationHtmlTemplate; private Template systemCloseNotificationHtmlTemplate; private Template hintNotificationHtmlTemplate; private Template needMessageNotificationHtmlTemplate; private Template systemDeactivateNotificationHtmlTemplate; public WonOwnerMailSender() { velocityEngine = new VelocityEngine(); Properties properties = new Properties(); properties.setProperty("resource.loader", "file"); properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); velocityEngine.init(properties); conversationNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/conversation-notification-html.vm"); connectNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/connect-notification-html.vm"); closeNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/close-notification-html.vm"); systemCloseNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/systemclose-notification-html.vm"); hintNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/hint-notification-html.vm"); needMessageNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/needmessage-notification-html.vm"); systemDeactivateNotificationHtmlTemplate = velocityEngine.getTemplate("mail-templates/system-deactivate-notification-html.vm"); } public void setWonMailSender(WonMailSender wonMailSender) { this.wonMailSender = wonMailSender; } private VelocityContext createContext(String toEmail, String localNeed, String remoteNeed, String localConnection, String textMsg) { String ownerAppLink = uriService.getOwnerProtocolOwnerURI().toString(); VelocityContext velocityContext = new VelocityContext(); if (remoteNeed!= null) { Dataset needDataset = linkedDataSource.getDataForResource(URI.create(remoteNeed)); DefaultNeedModelWrapper remoteNeedWrapper = new DefaultNeedModelWrapper(needDataset); String remoteNeedTitle = remoteNeedWrapper.getSomeTitleFromIsOrAll("en", "de"); velocityContext.put("remoteNeedTitle", remoteNeedTitle); String linkRemoteNeed = uriService.getOwnerProtocolOwnerURI() + OWNER_REMOTE_NEED_LINK + remoteNeed; velocityContext.put("linkRemoteNeed", linkRemoteNeed); } if (localNeed != null) { Dataset localNeedDataset = linkedDataSource.getDataForResource(URI.create(localNeed)); DefaultNeedModelWrapper localNeedWrapper = new DefaultNeedModelWrapper(localNeedDataset); String localNeedTitle = localNeedWrapper.getSomeTitleFromIsOrAll("en","de"); String linkLocalNeed = ownerAppLink + OWNER_LOCAL_NEED_LINK + localNeed; velocityContext.put("linkLocalNeed", linkLocalNeed); velocityContext.put("localNeedTitle", localNeedTitle); } if (localConnection != null){ String linkConnection = ownerAppLink + String.format(OWNER_CONNECTION_LINK,localNeed, localConnection, ConnectionState.CONNECTED.getURI().toString()); velocityContext.put("linkConnection", linkConnection); } if (textMsg != null) { velocityContext.put("textMsg", textMsg); } return velocityContext; } public void sendConversationNotificationHtmlMessage(String toEmail, String localNeed, String remoteNeed, String localConnection, String textMsg) { if (textMsg != null && !textMsg.isEmpty()) { StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, remoteNeed, localConnection, textMsg); conversationNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_CONVERSATION_MESSAGE + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_CONVERSATION_MESSAGE, writer.toString()); } else { logger.warn("do not send notification conversation email to {} with empty message. Connection is: {}", toEmail, localConnection); } } public void sendConnectNotificationHtmlMessage(String toEmail, String localNeed, String remoteNeed, String localConnection, String textMsg) { StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, remoteNeed, localConnection, textMsg); connectNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_CONNECT + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_CONNECT, writer.toString()); } public void sendCloseNotificationHtmlMessage(String toEmail, String localNeed, String remoteNeed, String localConnection, String textMsg) { StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, remoteNeed, localConnection, textMsg); closeNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_CLOSE + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_CLOSE, writer.toString()); } public void sendHintNotificationMessageHtml(String toEmail, String localNeed, String remoteNeed, String localConnection) { StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, remoteNeed, localConnection, null); hintNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_MATCH + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_MATCH, writer.toString()); } public void sendNeedMessageNotificationHtmlMessage(String toEmail, String localNeed, String textMsg){ StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, null, null, textMsg); needMessageNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_NEED_MESSAGE + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_NEED_MESSAGE, writer.toString()); } public void sendSystemDeactivateNotificationHtmlMessage(String toEmail, String localNeed, String textMsg){ StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, null, null, textMsg); systemDeactivateNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_SYSTEM_DEACTIVATE + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_SYSTEM_DEACTIVATE, writer.toString()); } public void sendSystemCloseNotificationHtmlMessage(String toEmail, String localNeed, String remoteNeed, String localConnection, String textMsg) { StringWriter writer = new StringWriter(); VelocityContext context = createContext(toEmail, localNeed, remoteNeed, localConnection, textMsg); systemCloseNotificationHtmlTemplate.merge(context, writer); logger.debug("sending " + SUBJECT_SYSTEM_CLOSE + " to " + toEmail); this.wonMailSender.sendHtmlMessage(toEmail, SUBJECT_SYSTEM_CLOSE, writer.toString()); } }
package com.lsjwzh.widget.text; import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.Spanned; import android.text.style.ClickableSpan; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; public class ClickableSpanUtil { public static boolean handleClickableSpan(View view, Layout layout, Spanned buffer, Class<? extends Clickable> spanType, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= view.getPaddingLeft(); y -= view.getPaddingTop(); x += view.getScrollX(); y += view.getScrollY(); int line = layout.getLineForVertical(y); int off = getOffsetForHorizontal(view, layout, x, line); Clickable[] link = buffer.getSpans(off, off, spanType); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(view); } else if (buffer instanceof Spannable) { Selection.setSelection((Spannable) buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } else if (buffer instanceof Spannable) { Selection.removeSelection((Spannable) buffer); } } return false; } public static boolean handleClickableSpan(View view, Layout layout, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= view.getPaddingLeft(); y -= view.getPaddingTop(); x += view.getScrollX(); y += view.getScrollY(); int line = layout.getLineForVertical(y); line = Math.min(layout.getLineCount() - 1, line); // lineline count int off = getOffsetForHorizontal(view, layout, x, line); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(view); } else { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } else { Selection.removeSelection(buffer); } } return false; } private static int getOffsetForHorizontal(View view, Layout layout, int x, int line) { if (view.getWidth() > layout.getWidth()) { if (view instanceof FastTextView) { int gravity = ((FastTextView) view).getGravity(); int translateX; int horizontalGravity = gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; switch (horizontalGravity) { default: case Gravity.LEFT: translateX = view.getPaddingLeft(); break; case Gravity.CENTER_HORIZONTAL: translateX = view.getPaddingLeft() + (((FastTextView) view).getInnerWidth() - layout .getWidth()) / 2; break; case Gravity.RIGHT: translateX = view.getPaddingLeft() + ((FastTextView) view).getInnerWidth() - layout .getWidth(); break; } x -= translateX; } } try { return layout.getOffsetForHorizontal(line, x); } catch (Throwable e) { e.printStackTrace(); } return layout.getLineEnd(line); } public interface Clickable { /** * Performs the click action associated with this span. */ void onClick(View widget); } }
package com.rnfs; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import android.os.StatFs; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.util.Base64; import android.util.SparseArray; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.net.URL; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RNFSManager extends ReactContextBaseJavaModule { private static final String RNFSDocumentDirectoryPath = "RNFSDocumentDirectoryPath"; private static final String RNFSExternalDirectoryPath = "RNFSExternalDirectoryPath"; private static final String RNFSExternalStorageDirectoryPath = "RNFSExternalStorageDirectoryPath"; private static final String RNFSPicturesDirectoryPath = "RNFSPicturesDirectoryPath"; private static final String RNFSTemporaryDirectoryPath = "RNFSTemporaryDirectoryPath"; private static final String RNFSCachesDirectoryPath = "RNFSCachesDirectoryPath"; private static final String RNFSExternalCachesDirectoryPath = "RNFSExternalCachesDirectoryPath"; private static final String RNFSDocumentDirectory = "RNFSDocumentDirectory"; private static final String RNFSFileTypeRegular = "RNFSFileTypeRegular"; private static final String RNFSFileTypeDirectory = "RNFSFileTypeDirectory"; private SparseArray<Downloader> downloaders = new SparseArray<Downloader>(); private SparseArray<Uploader> uploaders = new SparseArray<Uploader>(); private ReactApplicationContext reactContext; public RNFSManager(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNFSManager"; } private Uri getFileUri(String filepath) throws IORejectionException { Uri uri = Uri.parse(filepath); if (uri.getScheme() == null) { // No prefix, assuming that provided path is absolute path to file File file = new File(filepath); if (file.isDirectory()) { throw new IORejectionException("EISDIR", "EISDIR: illegal operation on a directory, read '" + filepath + "'"); } uri = Uri.parse("file://" + filepath); } return uri; } private String getOriginalFilepath(String filepath) throws IORejectionException { Uri uri = getFileUri(filepath); String originalFilepath = filepath; if (uri.getScheme().equals("content")) { try { Cursor cursor = reactContext.getContentResolver().query(uri, null, null, null, null); if (cursor.moveToFirst()) { originalFilepath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } } catch (IllegalArgumentException ignored) { } } return originalFilepath; } private InputStream getInputStream(String filepath) throws IORejectionException { Uri uri = getFileUri(filepath); InputStream stream; try { stream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException ex) { throw new IORejectionException("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } if (stream == null) { throw new IORejectionException("ENOENT", "ENOENT: could not open an input stream for '" + filepath + "'"); } return stream; } private OutputStream getOutputStream(String filepath, boolean append) throws IORejectionException { Uri uri = getFileUri(filepath); OutputStream stream; try { stream = reactContext.getContentResolver().openOutputStream(uri, append ? "wa" : "w"); } catch (FileNotFoundException ex) { throw new IORejectionException("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } if (stream == null) { throw new IORejectionException("ENOENT", "ENOENT: could not open an output stream for '" + filepath + "'"); } return stream; } private static byte[] getInputStreamBytes(InputStream inputStream) throws IOException { byte[] bytesResult; ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; try { int len; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } bytesResult = byteBuffer.toByteArray(); } finally { try { byteBuffer.close(); } catch (IOException ignored) { } } return bytesResult; } @ReactMethod public void writeFile(String filepath, String base64Content, ReadableMap options, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); OutputStream outputStream = getOutputStream(filepath, false); outputStream.write(bytes); outputStream.close(); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void appendFile(String filepath, String base64Content, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); OutputStream outputStream = getOutputStream(filepath, true); outputStream.write(bytes); outputStream.close(); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void write(String filepath, String base64Content, int position, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); if (position < 0) { OutputStream outputStream = getOutputStream(filepath, true); outputStream.write(bytes); outputStream.close(); } else { RandomAccessFile file = new RandomAccessFile(filepath, "rw"); file.seek(position); file.write(bytes); file.close(); } promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void exists(String filepath, Promise promise) { try { File file = new File(filepath); promise.resolve(file.exists()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void readFile(String filepath, Promise promise) { try { InputStream inputStream = getInputStream(filepath); byte[] inputData = getInputStreamBytes(inputStream); String base64Content = Base64.encodeToString(inputData, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void read(String filepath, int length, int position, Promise promise) { try { InputStream inputStream = getInputStream(filepath); byte[] buffer = new byte[length]; inputStream.skip(position); int bytesRead = inputStream.read(buffer, 0, length); String base64Content = Base64.encodeToString(buffer, 0, bytesRead, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void readFileAssets(String filepath, Promise promise) { InputStream stream = null; try { // ensure isn't a directory AssetManager assetManager = getReactApplicationContext().getAssets(); stream = assetManager.open(filepath, 0); if (stream == null) { reject(promise, filepath, new Exception("Failed to open file")); return; } byte[] buffer = new byte[stream.available()]; stream.read(buffer); String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } finally { if (stream != null) { try { stream.close(); } catch (IOException ignored) { } } } } @ReactMethod public void hash(String filepath, String algorithm, Promise promise) { try { Map<String, String> algorithms = new HashMap<>(); algorithms.put("md5", "MD5"); algorithms.put("sha1", "SHA-1"); algorithms.put("sha224", "SHA-224"); algorithms.put("sha256", "SHA-256"); algorithms.put("sha384", "SHA-384"); algorithms.put("sha512", "SHA-512"); if (!algorithms.containsKey(algorithm)) throw new Exception("Invalid hash algorithm"); File file = new File(filepath); if (file.isDirectory()) { rejectFileIsDirectory(promise); return; } if (!file.exists()) { rejectFileNotFound(promise, filepath); return; } MessageDigest md = MessageDigest.getInstance(algorithms.get(algorithm)); FileInputStream inputStream = new FileInputStream(filepath); byte[] buffer = new byte[1024 * 10]; // 10 KB Buffer int read; while ((read = inputStream.read(buffer)) != -1) { md.update(buffer, 0, read); } StringBuilder hexString = new StringBuilder(); for (byte digestByte : md.digest()) hexString.append(String.format("%02x", digestByte)); promise.resolve(hexString.toString()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void moveFile(String filepath, String destPath, ReadableMap options, Promise promise) { try { File inFile = new File(filepath); if (!inFile.renameTo(new File(destPath))) { new CopyFileTask() { @Override protected void onPostExecute (Exception ex) { if (ex == null) { inFile.delete(); promise.resolve(true); } else { ex.printStackTrace(); reject(promise, filepath, ex); } } }.execute(filepath, destPath); } else { promise.resolve(true); } } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void copyFile(final String filepath, final String destPath, ReadableMap options, final Promise promise) { new CopyFileTask() { @Override protected void onPostExecute (Exception ex) { if (ex == null) { promise.resolve(null); } else { ex.printStackTrace(); reject(promise, filepath, ex); } } }.execute(filepath, destPath); } private class CopyFileTask extends AsyncTask<String, Void, Exception> { protected Exception doInBackground(String... paths) { try { String filepath = paths[0]; String destPath = paths[1]; InputStream in = getInputStream(filepath); OutputStream out = getOutputStream(destPath, false); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); Thread.yield(); } in.close(); out.close(); return null; } catch (Exception ex) { return ex; } } } @ReactMethod public void readDir(String directory, Promise promise) { try { File file = new File(directory); if (!file.exists()) throw new Exception("Folder does not exist"); File[] files = file.listFiles(); WritableArray fileMaps = Arguments.createArray(); for (File childFile : files) { WritableMap fileMap = Arguments.createMap(); fileMap.putDouble("mtime", (double) childFile.lastModified() / 1000); fileMap.putString("name", childFile.getName()); fileMap.putString("path", childFile.getAbsolutePath()); fileMap.putInt("size", (int) childFile.length()); fileMap.putInt("type", childFile.isDirectory() ? 1 : 0); fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (Exception ex) { ex.printStackTrace(); reject(promise, directory, ex); } } @ReactMethod public void readDirAssets(String directory, Promise promise) { try { AssetManager assetManager = getReactApplicationContext().getAssets(); String[] list = assetManager.list(directory); WritableArray fileMaps = Arguments.createArray(); for (String childFile : list) { WritableMap fileMap = Arguments.createMap(); fileMap.putString("name", childFile); String path = directory.isEmpty() ? childFile : String.format("%s/%s", directory, childFile); // don't allow / at the start when directory is "" fileMap.putString("path", path); int length = 0; boolean isDirectory = true; try { AssetFileDescriptor assetFileDescriptor = assetManager.openFd(path); if (assetFileDescriptor != null) { length = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); isDirectory = false; } } catch (IOException ex) { //.. ah.. is a directory or a compressed file? isDirectory = ex.getMessage().indexOf("compressed") == -1; } fileMap.putInt("size", length); fileMap.putInt("type", isDirectory ? 1 : 0); // if 0, probably a folder.. fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (IOException e) { reject(promise, directory, e); } } @ReactMethod public void copyFileAssets(String assetPath, String destination, Promise promise) { AssetManager assetManager = getReactApplicationContext().getAssets(); try { InputStream in = assetManager.open(assetPath); copyInputStream(in, assetPath, destination, promise); } catch (IOException e) { // Default error message is just asset name, so make a more helpful error here. reject(promise, assetPath, new Exception(String.format("Asset '%s' could not be opened", assetPath))); } } @ReactMethod public void existsAssets(String filepath, Promise promise) { try { AssetManager assetManager = getReactApplicationContext().getAssets(); try { String[] list = assetManager.list(filepath); if (list != null && list.length > 0) { promise.resolve(true); return; } } catch (Exception ignored) { //.. probably not a directory then } // Attempt to open file (win = exists) InputStream fileStream = null; try { fileStream = assetManager.open(filepath); promise.resolve(true); } catch (Exception ex) { promise.resolve(false); // don't throw an error, resolve false } finally { if (fileStream != null) { try { fileStream.close(); } catch (Exception ignored) { } } } } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } /** * Internal method for copying that works with any InputStream * * @param in InputStream from assets or file * @param source source path (only used for logging errors) * @param destination destination path * @param promise React Callback */ private void copyInputStream(InputStream in, String source, String destination, Promise promise) { OutputStream out = null; try { out = getOutputStream(destination, false); byte[] buffer = new byte[1024 * 10]; // 10k buffer int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } // Success! promise.resolve(null); } catch (Exception ex) { reject(promise, source, new Exception(String.format("Failed to copy '%s' to %s (%s)", source, destination, ex.getLocalizedMessage()))); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } if (out != null) { try { out.close(); } catch (IOException ignored) { } } } } @ReactMethod public void setReadable(String filepath, Boolean readable, Boolean ownerOnly, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); file.setReadable(readable, ownerOnly); promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void stat(String filepath, Promise promise) { try { String originalFilepath = getOriginalFilepath(filepath); File file = new File(originalFilepath); if (!file.exists()) throw new Exception("File does not exist"); WritableMap statMap = Arguments.createMap(); statMap.putInt("ctime", (int) (file.lastModified() / 1000)); statMap.putInt("mtime", (int) (file.lastModified() / 1000)); statMap.putInt("size", (int) file.length()); statMap.putInt("type", file.isDirectory() ? 1 : 0); statMap.putString("originalFilepath", originalFilepath); promise.resolve(statMap); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void unlink(String filepath, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); DeleteRecursive(file); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); } } fileOrDirectory.delete(); } @ReactMethod public void mkdir(String filepath, ReadableMap options, Promise promise) { try { File file = new File(filepath); file.mkdirs(); boolean exists = file.exists(); if (!exists) throw new Exception("Directory could not be created"); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } @ReactMethod public void downloadFile(final ReadableMap options, final Promise promise) { try { File file = new File(options.getString("toFile")); URL url = new URL(options.getString("fromUrl")); final int jobId = options.getInt("jobId"); ReadableMap headers = options.getMap("headers"); int progressDivider = options.getInt("progressDivider"); int readTimeout = options.getInt("readTimeout"); int connectionTimeout = options.getInt("connectionTimeout"); DownloadParams params = new DownloadParams(); params.src = url; params.dest = file; params.headers = headers; params.progressDivider = progressDivider; params.readTimeout = readTimeout; params.connectionTimeout = connectionTimeout; params.onTaskCompleted = new DownloadParams.OnTaskCompleted() { public void onTaskCompleted(DownloadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putInt("bytesWritten", res.bytesWritten); promise.resolve(infoMap); } else { reject(promise, options.getString("toFile"), res.exception); } } }; params.onDownloadBegin = new DownloadParams.OnDownloadBegin() { public void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers) { WritableMap headersMap = Arguments.createMap(); for (Map.Entry<String, String> entry : headers.entrySet()) { headersMap.putString(entry.getKey(), entry.getValue()); } WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("statusCode", statusCode); data.putInt("contentLength", contentLength); data.putMap("headers", headersMap); sendEvent(getReactApplicationContext(), "DownloadBegin-" + jobId, data); } }; params.onDownloadProgress = new DownloadParams.OnDownloadProgress() { public void onDownloadProgress(int contentLength, int bytesWritten) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("contentLength", contentLength); data.putInt("bytesWritten", bytesWritten); sendEvent(getReactApplicationContext(), "DownloadProgress-" + jobId, data); } }; Downloader downloader = new Downloader(); downloader.execute(params); this.downloaders.put(jobId, downloader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, options.getString("toFile"), ex); } } @ReactMethod public void stopDownload(int jobId) { Downloader downloader = this.downloaders.get(jobId); if (downloader != null) { downloader.stop(); } } @ReactMethod public void uploadFiles(final ReadableMap options, final Promise promise) { try { ReadableArray files = options.getArray("files"); URL url = new URL(options.getString("toUrl")); final int jobId = options.getInt("jobId"); ReadableMap headers = options.getMap("headers"); ReadableMap fields = options.getMap("fields"); String method = options.getString("method"); ArrayList<ReadableMap> fileList = new ArrayList<>(); UploadParams params = new UploadParams(); for(int i =0;i<files.size();i++){ fileList.add(files.getMap(i)); } params.src = url; params.files =fileList; params.headers = headers; params.method=method; params.fields=fields; params.onUploadComplete = new UploadParams.onUploadComplete() { public void onUploadComplete(UploadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putMap("headers",res.headers); infoMap.putString("body",res.body); promise.resolve(infoMap); } else { reject(promise, options.getString("toUrl"), res.exception); } } }; params.onUploadBegin = new UploadParams.onUploadBegin() { public void onUploadBegin() { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); sendEvent(getReactApplicationContext(), "UploadBegin-" + jobId, data); } }; params.onUploadProgress = new UploadParams.onUploadProgress() { public void onUploadProgress(int totalBytesExpectedToSend,int totalBytesSent) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("totalBytesExpectedToSend", totalBytesExpectedToSend); data.putInt("totalBytesSent", totalBytesSent); sendEvent(getReactApplicationContext(), "UploadProgress-" + jobId, data); } }; Uploader uploader = new Uploader(); uploader.execute(params); this.uploaders.put(jobId, uploader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, options.getString("toUrl"), ex); } } @ReactMethod public void stopUpload(int jobId) { Uploader uploader = this.uploaders.get(jobId); if (uploader != null) { uploader.stop(); } } @ReactMethod public void pathForBundle(String bundleNamed, Promise promise) { // TODO: Not sure what equivalent would be? } @ReactMethod public void pathForGroup(String bundleNamed, Promise promise) { // TODO: Not sure what equivalent would be? } @ReactMethod public void getFSInfo(Promise promise) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long totalSpace; long freeSpace; if (android.os.Build.VERSION.SDK_INT >= 18) { totalSpace = stat.getTotalBytes(); freeSpace = stat.getFreeBytes(); } else { long blockSize = stat.getBlockSize(); totalSpace = blockSize * stat.getBlockCount(); freeSpace = blockSize * stat.getAvailableBlocks(); } WritableMap info = Arguments.createMap(); info.putDouble("totalSpace", (double) totalSpace); // Int32 too small, must use Double info.putDouble("freeSpace", (double) freeSpace); promise.resolve(info); } @ReactMethod public void touch(String filepath, double mtime, double ctime, Promise promise) { try { File file = new File(filepath); promise.resolve(file.setLastModified((long) mtime)); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void getAllExternalFilesDirs(Promise promise){ File[] allExternalFilesDirs = this.getReactApplicationContext().getExternalFilesDirs(null); WritableArray fs = Arguments.createArray(); for (File f : allExternalFilesDirs) { fs.pushString(f.getAbsolutePath()); } promise.resolve(fs); } private void reject(Promise promise, String filepath, Exception ex) { if (ex instanceof FileNotFoundException) { rejectFileNotFound(promise, filepath); return; } if (ex instanceof IORejectionException) { IORejectionException ioRejectionException = (IORejectionException) ex; promise.reject(ioRejectionException.getCode(), ioRejectionException.getMessage()); return; } promise.reject(null, ex.getMessage()); } private void rejectFileNotFound(Promise promise, String filepath) { promise.reject("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } private void rejectFileIsDirectory(Promise promise) { promise.reject("EISDIR", "EISDIR: illegal operation on a directory, read"); } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(RNFSDocumentDirectory, 0); constants.put(RNFSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath()); constants.put(RNFSTemporaryDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(RNFSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); constants.put(RNFSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(RNFSFileTypeRegular, 0); constants.put(RNFSFileTypeDirectory, 1); File externalStorageDirectory = Environment.getExternalStorageDirectory(); if (externalStorageDirectory != null) { constants.put(RNFSExternalStorageDirectoryPath, externalStorageDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalStorageDirectoryPath, null); } File externalDirectory = this.getReactApplicationContext().getExternalFilesDir(null); if (externalDirectory != null) { constants.put(RNFSExternalDirectoryPath, externalDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalDirectoryPath, null); } File externalCachesDirectory = this.getReactApplicationContext().getExternalCacheDir(); if (externalCachesDirectory != null) { constants.put(RNFSExternalCachesDirectoryPath, externalCachesDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalCachesDirectoryPath, null); } return constants; } }
package communication; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; /** * * @author maikel */ public class CaptureAudio implements Runnable { TargetDataLine line; Thread thread; String errStr; double duration; AudioInputStream audioInputStream; public void start() { errStr = null; thread = new Thread(this); thread.setName("Capture"); thread.start(); } public void stop() { thread = null; } private void shutDown(String message) { if ((errStr = message) != null && thread != null) { thread = null; System.err.println(errStr); } } @Override public void run() { duration = 0; audioInputStream = null; // define the required attributes for our line, // and make sure a compatible line is supported. AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED; float rate = 44100.0f; int channels = 2; int frameSize = 4; int sampleSize = 16; boolean bigEndian = true; AudioFormat format = new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize / 8) * channels, rate, bigEndian); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { shutDown("Line matching " + info + " not supported."); return; } // get and open the target data line for capture. try { line = (TargetDataLine) AudioSystem.getLine(info); line.open(format, line.getBufferSize()); } catch (LineUnavailableException ex) { shutDown("Unable to open the line: " + ex); return; } catch (SecurityException ex) { shutDown(ex.toString()); //JavaSound.showInfoDialog(); return; } catch (Exception ex) { shutDown(ex.toString()); return; } // play back the captured audio data ByteArrayOutputStream out = new ByteArrayOutputStream(); int frameSizeInBytes = format.getFrameSize(); int bufferLengthInFrames = line.getBufferSize() / 8; int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes; byte[] data = new byte[bufferLengthInBytes]; int numBytesRead; line.start(); while (thread != null) { if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) { break; } out.write(data, 0, numBytesRead); } // we reached the end of the stream. // stop and close the line. line.stop(); line.close(); line = null; // stop and close the output stream try { out.flush(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } // load bytes into the audio input stream for playback byte audioBytes[] = out.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes); audioInputStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes); long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format .getFrameRate()); duration = milliseconds / 1000.0; try { audioInputStream.reset(); } catch (Exception ex) { ex.printStackTrace(); return; } } } // End class Capture
package zjava.collection; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; /** * Early draft of HashTable. * * <p> Doesn't permit <tt>null</tt> value. * * @param <E> - the type of entries in this hash table * * @since Zjava 1.0 * * @author Ivan Zaitsau */ class HashTable<E> implements Iterable<E>, Cloneable, java.io.Serializable { private static final long serialVersionUID = 201612081900L; private static final byte COLLISION_HITS_THRESHOLD = 12; private static class Entry<E> implements Cloneable, java.io.Serializable { private static final long serialVersionUID = 201612081900L; final int hash; final E key; Entry<E> next; Entry(int hash, E key, Entry<E> next) { this.hash = hash; this.key = key; this.next = next; } public Entry<E> clone() { try { @SuppressWarnings("unchecked") Entry<E> clone = (Entry<E>) super.clone(); if (next != null) clone.next = next.clone(); return clone(); } catch (CloneNotSupportedException e) { // - should never be thrown since we are Cloneable throw new InternalError(); } } } private static class Block<E> implements Iterable<E>, Cloneable, java.io.Serializable { private static final long serialVersionUID = 201612081900L; static final int ADDRESS_BITS = 6; static final int SIZE = 1 << ADDRESS_BITS; private static final int COLLISIONS_ADDRESS_BITS = 4; private static final int COLLISIONS_SIZE = 1 << COLLISIONS_ADDRESS_BITS; private static final int ASSOCIATIVITY = 6; // - essential variables private E[] values; private int[] hashes; private Entry<E>[] collisions; // - service variables private final byte rank; private byte collisionHits; private static int valuesIndex(final int hash) { return hash & (SIZE - 1); } private static int collisionsIndex(final int hash) { return hash & (COLLISIONS_SIZE - 1); } public Block(int rank) { if (0 > rank | rank >= 32) throw new IllegalArgumentException(); this.rank = (byte) rank; } private void incCollisionHits() { if (collisionHits < Byte.MAX_VALUE) collisionHits++; } public byte getCollisionHits() { return collisionHits; } public void resetCollisionHits() { collisionHits = 0; } @SuppressWarnings("unchecked") private void lazyInitValues() { if (values == null) { hashes = new int[SIZE + ASSOCIATIVITY]; values = (E[]) new Object[SIZE + ASSOCIATIVITY]; } } @SuppressWarnings("unchecked") private void lazyInitCollisions() { if (collisions == null) { collisions = new Entry[COLLISIONS_SIZE]; } } public boolean add(final int hash, final E key) { if (contains(hash, key)) return false; // - look for free space in values lazyInitValues(); int idx = valuesIndex(hash); for (int i = 0; i < ASSOCIATIVITY; i++) { if (values[idx+i] == null) { hashes[idx+i] = hash; values[idx+i] = key; return true; } } // - add to collisions if no space left in "values" lazyInitCollisions(); idx = collisionsIndex(hash); collisions[idx] = new Entry<E>(hash, key, collisions[idx]); return true; } public boolean contains(final int hash, final E key) { // - check values if (values == null) return false; int idx = valuesIndex(hash); for (int i = 0; i < ASSOCIATIVITY; i++) if (hashes[idx+i] == hash && key.equals(values[idx+i])) return true; // - check collisions if (collisions == null) return false; Entry<E> entry = collisions[collisionsIndex(hash)]; while (entry != null) { incCollisionHits(); if (entry.hash == hash && entry.key.equals(key)) return true; entry = entry.next; } return false; } public boolean remove(final int hash, final E key) { // - check values if (values == null) return false; int idx = valuesIndex(hash); for (int i = 0; i < ASSOCIATIVITY; i++) if (hashes[idx+i] == hash && key.equals(values[idx+i])) { hashes[idx+i] = 0; values[idx+i] = null; return true; } // - check collisions if (collisions == null) return false; idx = collisionsIndex(hash); Entry<E> prev = null; Entry<E> entry = collisions[idx]; while (entry != null) { incCollisionHits(); if (entry.hash == hash && entry.key.equals(key)) { if (prev == null) collisions[idx] = entry.next; else prev.next = entry.next; return true; } prev = entry; entry = entry.next; } return false; } // - returns bits of the given hash related to given rank private static int rankedHash(final int hash, final int rank) { return (hash >>> ADDRESS_BITS) & ((1 << rank) - 1); } private boolean putToValues(Entry<E> entry) { int idx = valuesIndex(entry.hash); for (int i = 0; i < ASSOCIATIVITY; i++) if (values[idx+i] == null) { hashes[idx+i] = entry.hash; values[idx+i] = entry.key; return true; } return false; } public Block<E> extract(final int requestedRank, int hash) { if (requestedRank == rank) return this; hash = rankedHash(hash, requestedRank); Block<E> extracted = new Block<E>(requestedRank); // - extract values if (values == null) return extracted; for (int i = 0; i < values.length; i++) { if (rankedHash(hashes[i], requestedRank) == hash) { extracted.lazyInitValues(); extracted.hashes[i] = hashes[i]; extracted.values[i] = values[i]; hashes[i] = 0; values[i] = null; } } // - extract collisions and put them in values, if possible if (collisions == null) return extracted; for (int i = 0; i < collisions.length; i++) if (collisions[i] != null) { Entry<E> prev = null; Entry<E> entry = collisions[i]; while (entry != null) { // - try to put to values if (((rankedHash(entry.hash, requestedRank) == hash) ? extracted : this).putToValues(entry)) { entry = (prev == null) ? (collisions[i] = entry.next) : (prev.next = entry.next); } // - if not possible - move to collisions in extracted block / leave there else { if (rankedHash(entry.hash, requestedRank) == hash) { final Entry<E> next = (prev == null) ? (collisions[i] = entry.next) : (prev.next = entry.next); extracted.lazyInitCollisions(); entry.next = extracted.collisions[i]; extracted.collisions[i] = entry; entry = next; } else { entry = entry.next; } } } } return extracted; } public Iterator<E> iterator() { return new Iterator<E>() { private byte lastIndex = -1; private byte nextIndex = 0; private byte lastCollisionIndex = -1; private byte nextCollisionIndex = 0; private Entry<E> lastCollision = null; public boolean hasNext() { try { // - iteration over values if (values == null) return false; while (nextIndex < values.length && values[nextIndex] == null) nextIndex++; if (nextIndex < values.length) return true; // - iteration over collisions if (collisions == null) return false; if (lastCollision != null && lastCollision.next != null) return true; while (nextCollisionIndex < collisions.length && collisions[nextCollisionIndex] == null) nextCollisionIndex++; return (nextCollisionIndex < collisions.length); } catch (NullPointerException e) { throw new ConcurrentModificationException(); } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } public E next() { if (!hasNext()) throw new NoSuchElementException(); try { // - iteration over values lastIndex = nextIndex; if (lastIndex < values.length) { return values[lastIndex]; } // - iteration over collisions if (lastCollision == null || lastCollision.next == null) { lastCollisionIndex = nextCollisionIndex++; lastCollision = collisions[lastCollisionIndex]; } else { lastCollision = lastCollision.next; if (lastCollisionIndex < 0) lastCollisionIndex = (byte) ~lastCollisionIndex; } return lastCollision.key; } catch (NullPointerException e) { throw new ConcurrentModificationException(); } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } public void remove() { try { // - iteration over values if (lastIndex < 0) throw new IllegalStateException(); if (lastIndex < values.length) { values[lastIndex] = null; hashes[lastIndex] = 0; lastIndex = -1; } // - iteration over collisions if (lastCollisionIndex < 0) throw new IllegalStateException(); Entry<E> collision = collisions[lastCollisionIndex]; if (collision == lastCollision) { collisions[lastCollisionIndex] = collision.next; lastCollisionIndex = (byte) ~lastCollisionIndex; return; } while (collision.next != lastCollision) { collision = collision.next; } collision.next = lastCollision.next; lastCollisionIndex = (byte) ~lastCollisionIndex; } catch (NullPointerException e) { throw new ConcurrentModificationException(); } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } }; } @SuppressWarnings("unchecked") public Block<E> clone() { try { Block<E> clone = (Block<E>) super.clone(); clone.values = values.clone(); clone.hashes = hashes.clone(); if (collisions != null) { clone.collisions = new Entry[collisions.length]; for (int i = 0; i < collisions.length; i++) { if (collisions[i] != null) { clone.collisions[i] = collisions[i].clone(); } } } return clone(); } catch (CloneNotSupportedException e) { // - should never be thrown since we are Cloneable throw new InternalError(); } } } private Block<E>[] data; private long size; @SuppressWarnings("unchecked") private void init() { data = (Block<E>[]) new Block[1]; data[0] = new Block<E>(0); size = 0; } /** * Creates {@code HashTable}. */ public HashTable() { init(); } public long size() { return size; } private int blockIndex(final int hash) { return (hash >>> Block.ADDRESS_BITS) & (data.length - 1); } private void optimize(final int blockIndex, final int hash) { final Block<E> block = data[blockIndex]; if (block.getCollisionHits() >= COLLISION_HITS_THRESHOLD) { data[blockIndex] = block.extract(rank(), hash); block.resetCollisionHits(); } } public boolean add(int hash, E entry) { final int blockIndex = blockIndex(hash); optimize(blockIndex, hash); if (data[blockIndex].add(hash, entry)) { size++; return true; } return false; } public boolean contains(int hash, E entry) { final int blockIndex = blockIndex(hash); optimize(blockIndex, hash); return data[blockIndex].contains(hash, entry); } public boolean remove(int hash, E entry) { final int blockIndex = blockIndex(hash); optimize(blockIndex, hash); if (data[blockIndex].remove(hash, entry)) { size return true; } return false; } public void clear() { init(); } private int rank() { return Integer.bitCount(data.length - 1); } /** * Doubles size of this {@code HashTable} */ public void doubleTableSize() { final int oldLength = data.length; data = Arrays.copyOf(data, data.length); System.arraycopy(data, 0, data, oldLength, oldLength); } public Iterator<E> iterator() { return new Iterator<E>() { /** index of current data block */ private int i = 0; /** current block iterator */ Iterator<E> iter; /** previously used iterator to handle <tt>remove()</tt> calls */ Iterator<E> prev; /** used to track already visited blocks */ Set<Block<E>> visitedBlocks = new HashSet<Block<E>>(); public boolean hasNext() { while ((iter == null || !iter.hasNext()) && i < data.length) { if (visitedBlocks.add(data[i])) { iter = data[i].iterator(); } i++; } return (iter != null && iter.hasNext()); } public E next() { if (!hasNext()) throw new NoSuchElementException(); E next = iter.next(); prev = iter; return next; } public void remove() { if (prev == null) throw new IllegalStateException(); prev.remove(); prev = null; } }; } /** * Returns a shallow copy of this <tt>HashTable</tt> instance. * (The elements themselves are not cloned). * * @return a clone of this <tt>HashTable</tt> instance */ @SuppressWarnings("unchecked") public HashTable<E> clone() { try { HashTable<E> clone = (HashTable<E>) super.clone(); for (int i = 0; i < data.length; i++) { clone.data[i] = data[i].clone(); } return clone; } catch (CloneNotSupportedException e) { // - should never be thrown since we are Cloneable throw new InternalError(); } } }
package com.red.alert.config; public class API { // RedAlert API URL (no trailing slash) public static String API_ENDPOINT = "https://redalert.me"; // Define platform to be sent by our API public static String PLATFORM_IDENTIFIER = "android"; // Define platform for Pushy self test public static String PUSHY_PLATFORM_IDENTIFIER = "pushy"; }
package distributed.main; import distributed.database.DatabaseManager; import distributed.dto.GroupMessage; import distributed.dto.IMessage; import distributed.dto.LeaderMessage; import distributed.dto.PrivateMessage; import distributed.msg.MsgDialog; import distributed.net.DistributedCore; import distributed.net.Messenger; import distributed.net.Messenger.MessageCallback; import distributed.settings.SettingsDialog; import distributed.user.AccessFrame; import distributed.user.ChangeMessageDialog; import distributed.util.DateUtils; import distributed.util.DistributedKrypto; import distributed.util.SettingsProvider; import distributed.util.SettingsProvider.UserType; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * * @author kiefer */ public class MainFrame extends javax.swing.JFrame implements MessageCallback { private boolean contextMenu = true; /** * Creates new form MainFrame */ public MainFrame() { initComponents(); //Starte Programm Messenger.getInstance().addMessageListener(this); if (SettingsProvider.getInstance().getUserInterface() != null) { try { DistributedCore.getInstance().configure(InetAddress.getByName(SettingsProvider.getInstance().getUserInterface())); } catch (UnknownHostException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } if (!SettingsProvider.getInstance().getUserGroup().equals("")) { DistributedCore.getInstance().joinGroup(SettingsProvider.getInstance().getUserGroup()); } jList1.setModel( new MyListModel(null)); jList1.addMouseListener( new MouseAdapter() { @Override public void mousePressed(MouseEvent e ) { showPopup(e); } @Override public void mouseReleased(MouseEvent e ) { showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger() && contextMenu) { showMenu(e); } } } ); jLabel1.setText("Hello " + SettingsProvider.getInstance().getUserName() + "!"); } public void showMenu(MouseEvent evt) { JPopupMenu menu = new JPopupMenu(); JMenuItem jMenuItemShare = new javax.swing.JMenuItem(); jMenuItemShare.setText("Share"); IMessage m = ((MyListModel) jList1.getModel()).getMessageAt(jList1.getSelectedIndex()); if (m.getSender().equals(SettingsProvider.getInstance().getUserName()) || SettingsProvider.getInstance().getUserType() == UserType.Moderator) { jMenuItemShare.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (jList1.getSelectedIndex() > -1) { showMessageDialog(null, ((MyListModel) jList1.getModel()).getMessageAt(jList1.getSelectedIndex())); } } }); } JMenuItem jMenuItemDirectMessage = new javax.swing.JMenuItem(); jMenuItemDirectMessage.setText("Direct Message"); jMenuItemDirectMessage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (jList1.getSelectedIndex() > -1) { IMessage m = ((MyListModel) jList1.getModel()).getMessageAt(jList1.getSelectedIndex()); if (m instanceof GroupMessage) { showMessageDialog(((GroupMessage) m).getSender(), m); } } } }); JMenuItem jMenuItemDeleteMessage = new javax.swing.JMenuItem(); jMenuItemDeleteMessage.setText("Delete Message"); jMenuItemDeleteMessage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("delete message"); if (jList1.getSelectedIndex() > -1) { IMessage m = ((MyListModel) jList1.getModel()).getMessageAt(jList1.getSelectedIndex()); if (m.getSender().equals(SettingsProvider.getInstance().getUserName()) || SettingsProvider.getInstance().getUserType() == UserType.Moderator) { DatabaseManager.getInstance().markAsDeleted((GroupMessage) m); MyListModel model = (MyListModel) jList1.getModel(); model.remove(jList1.getSelectedIndex()); jList1.revalidate(); jList1.repaint(); } } } }); JMenuItem jMenuItemChangeMessage = new javax.swing.JMenuItem(); jMenuItemChangeMessage.setText("Change Message"); jMenuItemChangeMessage.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("change message"); //TODO ABfrage ob der user rechte hat if (jList1.getSelectedIndex() > -1) { IMessage m = ((MyListModel) jList1.getModel()).getMessageAt(jList1.getSelectedIndex()); if (m.getSender().equals(SettingsProvider.getInstance().getUserName())) { System.out.println("ich bin der user: valid"); Frame ChangeMessageDialog = null; ChangeMessageDialog changeDialog = new ChangeMessageDialog(MainFrame.this, true); changeDialog.setText(m); //set jtextarea in the dialog changeDialog.setVisible(true); MyListModel model = (MyListModel) jList1.getModel(); model.changeMsg(jList1.getSelectedIndex(), changeDialog.getText()); jList1.revalidate(); jList1.repaint(); } } } }); menu.add(jMenuItemChangeMessage); menu.add(new JPopupMenu.Separator()); menu.add(jMenuItemDeleteMessage); menu.add(new JPopupMenu.Separator()); menu.add(jMenuItemDirectMessage); menu.add(new JPopupMenu.Separator()); menu.add(jMenuItemShare); menu.show(evt.getComponent(), evt.getX(), evt.getY()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jToolBar1 = new javax.swing.JToolBar(); jButtonNewMsg = new javax.swing.JButton(); filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0)); jButtonAbout = new javax.swing.JButton(); jButtonSettings = new javax.swing.JButton(); jButtonLogout = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Statusleiste"); jToolBar1.setFloatable(false); jToolBar1.setRollover(true); jButtonNewMsg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/distributed/icons/Mail_32x32.png"))); // NOI18N jButtonNewMsg.setText("New Message"); jButtonNewMsg.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jButtonNewMsg.setBorderPainted(false); jButtonNewMsg.setFocusable(false); jButtonNewMsg.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonNewMsg.setMinimumSize(new java.awt.Dimension(100, 50)); jButtonNewMsg.setPreferredSize(new java.awt.Dimension(75, 50)); jButtonNewMsg.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonNewMsg.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButtonNewMsgMouseClicked(evt); } }); jButtonNewMsg.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonNewMsgActionPerformed(evt); } }); jToolBar1.add(jButtonNewMsg); jToolBar1.add(filler3); jButtonAbout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/distributed/icons/Information_32x32.png"))); // NOI18N jButtonAbout.setText("About"); jButtonAbout.setBorderPainted(false); jButtonAbout.setFocusable(false); jButtonAbout.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonAbout.setMinimumSize(new java.awt.Dimension(100, 50)); jButtonAbout.setPreferredSize(new java.awt.Dimension(75, 50)); jButtonAbout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonAbout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAboutActionPerformed(evt); } }); jToolBar1.add(jButtonAbout); jButtonSettings.setIcon(new javax.swing.ImageIcon(getClass().getResource("/distributed/icons/Options_32x32.png"))); // NOI18N jButtonSettings.setText("Settings"); jButtonSettings.setBorderPainted(false); jButtonSettings.setFocusable(false); jButtonSettings.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonSettings.setMinimumSize(new java.awt.Dimension(100, 50)); jButtonSettings.setPreferredSize(new java.awt.Dimension(75, 50)); jButtonSettings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonSettings.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSettingsActionPerformed(evt); } }); jToolBar1.add(jButtonSettings); jButtonLogout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/distributed/icons/Link_32x32.png"))); // NOI18N jButtonLogout.setText("Logout"); jButtonLogout.setBorderPainted(false); jButtonLogout.setFocusable(false); jButtonLogout.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); jButtonLogout.setMinimumSize(new java.awt.Dimension(100, 50)); jButtonLogout.setPreferredSize(new java.awt.Dimension(75, 50)); jButtonLogout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButtonLogout.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButtonLogoutMouseClicked(evt); } }); jButtonLogout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLogoutActionPerformed(evt); } }); jToolBar1.add(jButtonLogout); jList1.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane2.setViewportView(jList1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane2) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonLogoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonLogoutMouseClicked }//GEN-LAST:event_jButtonLogoutMouseClicked private void jButtonNewMsgMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonNewMsgMouseClicked }//GEN-LAST:event_jButtonNewMsgMouseClicked private void jButtonNewMsgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewMsgActionPerformed showMessageDialog(null, null); }//GEN-LAST:event_jButtonNewMsgActionPerformed private void jButtonLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLogoutActionPerformed this.setVisible(false); if (SettingsProvider.getInstance().getUserType() == SettingsProvider.UserType.MODERATOR) { DistributedCore.getInstance().isLeader = false; DistributedCore.getInstance().disconnectLeaderChannel(); SettingsProvider.getInstance().storeUserType(SettingsProvider.UserType.USER); } AccessFrame mAccessFrame = new AccessFrame(); mAccessFrame.setLocationRelativeTo(this); mAccessFrame.setVisible(true); }//GEN-LAST:event_jButtonLogoutActionPerformed private void jButtonSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSettingsActionPerformed JFrame rootWindow = (JFrame) SwingUtilities.getWindowAncestor(this); SettingsDialog dialog = new SettingsDialog(rootWindow, true); dialog.setTitle("Settings"); dialog.setLocationRelativeTo(rootWindow); dialog.setVisible(true); }//GEN-LAST:event_jButtonSettingsActionPerformed private void jButtonAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAboutActionPerformed JFrame rootWindow = (JFrame) SwingUtilities.getWindowAncestor(this); AboutDialog dialog = new AboutDialog(rootWindow, true); dialog.setTitle("About"); dialog.setLocationRelativeTo(rootWindow); dialog.setVisible(true); }//GEN-LAST:event_jButtonAboutActionPerformed private void showMessageDialog(String reciever, IMessage message) { JFrame rootWindow = (JFrame) SwingUtilities.getWindowAncestor(this); MsgDialog dialog = new MsgDialog(rootWindow, true, message, reciever); if (message != null && reciever == null) { dialog.setTitle("Share Message"); } else { dialog.setTitle("New Message"); } dialog.setLocationRelativeTo(rootWindow); dialog.setVisible(true); IMessage m = dialog.getMessage(); if (m != null) { if (m instanceof PrivateMessage) { Messenger.getInstance().sendMessage((PrivateMessage) m); } else if (m instanceof GroupMessage) { Messenger.getInstance().sendGroupMessage((GroupMessage) m); } else if (m instanceof LeaderMessage) { Messenger.getInstance().sendLeaderMessage((LeaderMessage) m); } } else { System.out.println("Keine Nachricht übergeben."); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { /*for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } }*/ javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainFrame().setVisible(true); } }); } @Override public void messageReceived(IMessage msg) { ((MyListModel) jList1.getModel()).addElement(msg); } class MyListModel extends AbstractListModel { private final ArrayList<IMessage> messages; public MyListModel(ArrayList<IMessage> messages) { this.messages = new ArrayList<>(); } @Override public int getSize() { return messages.size(); } @Override public String getElementAt(int index) { IMessage m = messages.get(index); //TODO Return the object StringBuilder sb = new StringBuilder(); if (m instanceof GroupMessage) { GroupMessage gm = ((GroupMessage) messages.get(index)); sb.append("[").append(DateUtils.getTimeFormatAsString(gm.getSendDate())).append("]"); sb.append("von ").append(gm.getSender()).append(": "); sb.append(new String(gm.getMessage())); return sb.toString(); } else if (m instanceof PrivateMessage) { PrivateMessage pm = ((PrivateMessage) messages.get(index)); sb.append("[").append(DateUtils.getTimeFormatAsString(pm.getSendDate())).append("]"); sb.append("von ").append(pm.getSender()).append(": "); sb.append(DistributedKrypto.getInstance().decryptMessage(pm.getMessage())).append(" (privat)"); return sb.toString(); } else if ((m instanceof LeaderMessage) && (SettingsProvider.getInstance().getUserType() == SettingsProvider.UserType.MODERATOR)) { LeaderMessage lm = ((LeaderMessage) messages.get(index)); sb.append("[").append(DateUtils.getTimeFormatAsString(lm.getSendDate())).append("]"); sb.append("von ").append(lm.getSender()).append(": "); sb.append(new String(lm.getMessage())).append(" (leader)"); return sb.toString(); } return null; } public void addElement(IMessage m) { messages.add(m); this.fireContentsChanged(this, this.getSize(), messages.size()); } public IMessage getMessageAt(int index) { return (IMessage) messages.get(index); } public void clear() { messages.clear(); } public ArrayList<IMessage> getMessages() { return messages; } public void remove(int position) { messages.remove(position); } public void changeMsg(int position, String newMsg) { IMessage msg = messages.get(position); msg.setMessage(newMsg.getBytes()); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.Box.Filler filler3; private javax.swing.JButton jButtonAbout; private javax.swing.JButton jButtonLogout; private javax.swing.JButton jButtonNewMsg; private javax.swing.JButton jButtonSettings; private javax.swing.JLabel jLabel1; private javax.swing.JList jList1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JToolBar jToolBar1; // End of variables declaration//GEN-END:variables }
package MastodonTypes; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import java.io.Serializable; public class Status extends RealmObject implements Serializable { private final static long serialVersionUID = 4983372382391510544L; @PrimaryKey @SerializedName("id") @Expose private long id; @SerializedName("created_at") @Expose private String createdAt; @SerializedName("in_reply_to_id") @Expose private String inReplyToId; @SerializedName("in_reply_to_account_id") @Expose private String inReplyToAccountId; @SerializedName("sensitive") @Expose private Boolean sensitive; @SerializedName("spoiler_text") @Expose private String spoilerText; @SerializedName("visibility") @Expose private String visibility; @SerializedName("application") @Expose private Application application; @SerializedName("account") @Expose private Account account; @SerializedName("media_attachments") @Expose private RealmList<MediaAttachment> mediaAttachments = null; @SerializedName("mentions") @Expose private RealmList<Mention> mentions = null; @SerializedName("tags") @Expose private RealmList<Tag> tags = null; @SerializedName("uri") @Expose private String uri; @SerializedName("content") @Expose private String content; @SerializedName("url") @Expose private String url; @SerializedName("reblogs_count") @Expose private Integer reblogsCount; @SerializedName("favourites_count") @Expose private Integer favouritesCount; @SerializedName("reblog") @Expose private Boost reblog; @SerializedName("favourited") @Expose private Boolean favourited; @SerializedName("reblogged") @Expose private Boolean reblogged; private boolean thisIsABoost; public Boolean getThisIsABoost() { return thisIsABoost; } public void setThisIsABoost(Boolean thisIsABoost) { this.thisIsABoost = thisIsABoost; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public Object getInReplyToId() { return inReplyToId; } public void setInReplyToId(String inReplyToId) { this.inReplyToId = inReplyToId; } public String getInReplyToAccountId() { return inReplyToAccountId; } public void setInReplyToAccountId(String inReplyToAccountId) { this.inReplyToAccountId = inReplyToAccountId; } public Boolean getSensitive() { return sensitive; } public void setSensitive(Boolean sensitive) { this.sensitive = sensitive; } public String getSpoilerText() { return spoilerText; } public void setSpoilerText(String spoilerText) { this.spoilerText = spoilerText; } public String getVisibility() { return visibility; } public void setVisibility(String visibility) { this.visibility = visibility; } public Application getApplication() { return application; } public void setApplication(Application application) { this.application = application; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } public RealmList<MediaAttachment> getMediaAttachments() { return mediaAttachments; } public void setMediaAttachments(RealmList<MediaAttachment> mediaAttachments) { this.mediaAttachments = mediaAttachments; } public RealmList<Mention> getMentions() { return mentions; } public void setMentions(RealmList<Mention> mentions) { this.mentions = mentions; } public RealmList<Tag> getTags() { return tags; } public void setTags(RealmList<Tag> tags) { this.tags = tags; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Integer getReblogsCount() { return reblogsCount; } public void setReblogsCount(Integer reblogsCount) { this.reblogsCount = reblogsCount; } public Integer getFavouritesCount() { return favouritesCount; } public void setFavouritesCount(Integer favouritesCount) { this.favouritesCount = favouritesCount; } public Boost getReblog() { return reblog; } public void setReblog(Boost reblog) { this.reblog = reblog; } public Boolean getFavourited() { return favourited; } public void setFavourited(Boolean favourited) { this.favourited = favourited; } public Boolean getReblogged() { return reblogged; } public void setReblogged(Boolean reblogged) { this.reblogged = reblogged; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public int hashCode() { return new HashCodeBuilder().append(id).append(createdAt).append(inReplyToId).append(inReplyToAccountId).append(sensitive).append(spoilerText).append(visibility).append(application).append(account).append(mediaAttachments).append(mentions).append(tags).append(uri).append(content).append(url).append(reblogsCount).append(favouritesCount).append(reblog).append(favourited).append(reblogged).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Status)) { return false; } Status rhs = ((Status) other); return new EqualsBuilder().append(id, rhs.id).append(createdAt, rhs.createdAt).append(inReplyToId, rhs.inReplyToId).append(inReplyToAccountId, rhs.inReplyToAccountId).append(sensitive, rhs.sensitive).append(spoilerText, rhs.spoilerText).append(visibility, rhs.visibility).append(application, rhs.application).append(account, rhs.account).append(mediaAttachments, rhs.mediaAttachments).append(mentions, rhs.mentions).append(tags, rhs.tags).append(uri, rhs.uri).append(content, rhs.content).append(url, rhs.url).append(reblogsCount, rhs.reblogsCount).append(favouritesCount, rhs.favouritesCount).append(reblog, rhs.reblog).append(favourited, rhs.favourited).append(reblogged, rhs.reblogged).isEquals(); } }
package com.chiorichan.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.FileChannel; /** * Class containing file utilities */ public class FileUtil { public static byte[] inputStream2Bytes( InputStream is ) throws IOException { return inputStream2ByteArray( is ).toByteArray(); } public static ByteArrayOutputStream inputStream2ByteArray( InputStream is ) throws IOException { int nRead; byte[] data = new byte[16384]; ByteArrayOutputStream bs = new ByteArrayOutputStream(); while ( (nRead = is.read( data, 0, data.length )) != -1 ) { bs.write( data, 0, nRead ); } bs.flush(); return bs; } /** * This method copies one file to another location * * @param inFile * the source filename * @param outFile * the target filename * @return true on success */ @SuppressWarnings( "resource" ) public static boolean copy( File inFile, File outFile ) { if ( !inFile.exists() ) return false; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream( inFile ).getChannel(); out = new FileOutputStream( outFile ).getChannel(); long pos = 0; long size = in.size(); while ( pos < size ) { pos += in.transferTo( pos, 10 * 1024 * 1024, out ); } } catch ( IOException ioe ) { return false; } finally { try { if ( in != null ) in.close(); if ( out != null ) out.close(); } catch ( IOException ioe ) { return false; } } return true; } }
package model.entity; import java.util.ArrayList; import exceptions.AggregatedProduct; public class Order { private int id; private ArrayList<Product> productsOfTheOrder; private State state; private String direction; public Order(int id, ArrayList<Product> productsOfTheOrder, State state, String direction) { this.id = id; this.productsOfTheOrder = productsOfTheOrder; this.state = state; this.direction = direction; } public void addproduct(Product product) { productsOfTheOrder.add(product); } public int getId() { return id; } public State getState() { if (isToSend()) { state = State.TO_SEND; } if (isRecived()) { state = State.RECEIVED; } else { state = State.RECEIVED; } return state; } public boolean isToSend() { for (Product product : productsOfTheOrder) { if (product.getState().equals(State.TO_SEND)) { return true; } } return false; } public boolean isSend() { for (Product product : productsOfTheOrder) { if (!product.getState().equals(State.SEND)) { return false; } } return true; } public boolean isRecived() { for (Product product : productsOfTheOrder) { if (product.getState().equals(State.RECEIVED)) { return false; } } return true; } public boolean isProductToOrder(Product product) { for (Product productFromOrder : productsOfTheOrder) { if (product.equals(productFromOrder)) { return true; } } return false; } public void addProduct(Product product) throws AggregatedProduct { if (!isProductToOrder(product)) { productsOfTheOrder.add(product); } else { throw new AggregatedProduct(); } } public String getDirection() { return direction; } }
package org.jfree.data.xy; import org.jfree.data.ComparableObjectItem; /** * A data item representing data in the form (x, y, deltaX, deltaY), intended * for use by the {@link VectorSeries} class. * * @since 1.0.6 */ public class VectorDataItem extends ComparableObjectItem { /** * Creates a new instance of <code>VectorDataItem</code>. * * @param x the x-value. * @param y the y-value. * @param deltaX the vector x. * @param deltaY the vector y. */ public VectorDataItem(double x, double y, double deltaX, double deltaY) { super(new XYCoordinate(x, y), new Vector(deltaX, deltaY)); } /** * Returns the x-value. * * @return The x-value (never <code>null</code>). */ public double getXValue() { XYCoordinate xy = (XYCoordinate) getComparable(); return xy.getX(); } /** * Returns the y-value. * * @return The y-value. */ public double getYValue() { XYCoordinate xy = (XYCoordinate) getComparable(); return xy.getY(); } /** * Returns the vector. * * @return The vector (possibly <code>null</code>). */ public Vector getVector() { return (Vector) getObject(); } /** * Returns the x-component for the vector. * * @return The x-component. */ public double getVectorX() { Vector vi = (Vector) getObject(); if (vi != null) { return vi.getX(); } else { return Double.NaN; } } /** * Returns the y-component for the vector. * * @return The y-component. */ public double getVectorY() { Vector vi = (Vector) getObject(); if (vi != null) { return vi.getY(); } else { return Double.NaN; } } }
package org.knowm.xchange.bitstamp; import java.io.IOException; import java.util.Arrays; import org.knowm.xchange.BaseExchange; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeSpecification; import org.knowm.xchange.bitstamp.dto.marketdata.BitstampPairInfo; import org.knowm.xchange.bitstamp.service.BitstampAccountService; import org.knowm.xchange.bitstamp.service.BitstampMarketDataService; import org.knowm.xchange.bitstamp.service.BitstampMarketDataServiceRaw; import org.knowm.xchange.bitstamp.service.BitstampTradeService; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.utils.nonce.CurrentNanosecondTimeIncrementalNonceFactory; import si.mazi.rescu.SynchronizedValueFactory; /** @author Matija Mazi */ public class BitstampExchange extends BaseExchange implements Exchange { private SynchronizedValueFactory nonceFactory = new CurrentNanosecondTimeIncrementalNonceFactory(); @Override protected void initServices() { this.marketDataService = new BitstampMarketDataService(this); this.tradeService = new BitstampTradeService(this); this.accountService = new BitstampAccountService(this); } @Override public ExchangeSpecification getDefaultExchangeSpecification() { ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName()); exchangeSpecification.setSslUri("https: exchangeSpecification.setHost("www.bitstamp.net"); exchangeSpecification.setPort(80); exchangeSpecification.setExchangeName("Bitstamp"); exchangeSpecification.setExchangeDescription( "Bitstamp is a Bitcoin exchange registered in Slovenia."); return exchangeSpecification; } @Override public SynchronizedValueFactory<Long> getNonceFactory() { return nonceFactory; } @Override public void remoteInit() throws IOException, ExchangeException { BitstampMarketDataServiceRaw dataService = (BitstampMarketDataServiceRaw) this.marketDataService; BitstampPairInfo[] bitstampPairInfos = dataService.getTradingPairsInfo(); exchangeMetaData = BitstampAdapters.adaptMetaData(Arrays.asList(bitstampPairInfos), exchangeMetaData); } }
package org.codehaus.xfire.aegis.type.java5; import java.util.Iterator; import javax.xml.namespace.QName; import org.codehaus.xfire.aegis.AbstractXFireAegisTest; import org.codehaus.xfire.aegis.AegisBindingProvider; import org.codehaus.xfire.aegis.type.Type; import org.codehaus.xfire.aegis.type.TypeMapping; import org.codehaus.xfire.aegis.type.basic.BeanType; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.codehaus.xfire.soap.SoapConstants; import org.jdom.Document; public class AnnotatedTypeTest extends AbstractXFireAegisTest { private TypeMapping tm; private Service service; public void setUp() throws Exception { super.setUp(); ObjectServiceFactory osf = (ObjectServiceFactory) getServiceFactory(); service = osf.create(AnnotatedService.class); getServiceRegistry().register(service); tm = ((AegisBindingProvider) osf.getBindingProvider()).getTypeMapping(service); } public void testTM() { assertTrue( tm.getTypeCreator() instanceof Java5TypeCreator ); } public void testType() { AnnotatedTypeInfo info = new AnnotatedTypeInfo(tm, AnnotatedBean1.class); Iterator elements = info.getElements(); assertTrue(elements.hasNext()); String element = (String) elements.next(); assertTrue(elements.hasNext()); element = (String) elements.next(); assertFalse(elements.hasNext()); Type custom = info.getType(element); // TODO: Fix custom types // assertTrue(custom instanceof CustomStringType); Iterator atts = info.getAttributes(); assertTrue(atts.hasNext()); String att = (String) atts.next(); assertFalse(atts.hasNext()); } public void testWSDL() throws Exception { Document wsdl = getWSDLDocument("AnnotatedService"); addNamespace("xsd", SoapConstants.XSD); assertValid("//xsd:complexType[@name='AnnotatedBean1']/xsd:sequence/xsd:element[@name='elementProperty']", wsdl); assertValid("//xsd:complexType[@name='AnnotatedBean1']/xsd:attribute[@name='attributeProperty']", wsdl); assertValid("//xsd:complexType[@name='AnnotatedBean1']/xsd:sequence/xsd:element[@name='bogusProperty']", wsdl); assertValid("//xsd:complexType[@name='AnnotatedBean2']/xsd:sequence/xsd:element[@name='element'][@type='xsd:string']", wsdl); assertValid("//xsd:complexType[@name='AnnotatedBean2']/xsd:attribute[@name='attribute'][@type='xsd:string']", wsdl); } public void testGetSetRequired() throws Exception { BeanType type = new BeanType(new AnnotatedTypeInfo(tm, BadBean.class)); type.setSchemaType(new QName("urn:foo", "BadBean")); assertFalse(type.getTypeInfo().getElements().hasNext()); type = new BeanType(new AnnotatedTypeInfo(tm, BadBean2.class)); type.setTypeClass(BadBean2.class); type.setSchemaType(new QName("urn:foo", "BadBean2")); assertFalse(type.getTypeInfo().getElements().hasNext()); } // This class only has a read property, no write public static class BadBean { private String string; public String getString() { return string; } } public static class BadBean2 { private String string; public void setString(String string) { this.string = string; } } }
package com.thoughtworks.xstream.core.util; import junit.framework.TestCase; import java.lang.ref.SoftReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ObjectIdDictionaryTest extends TestCase { public void testMapsIdsToObjectReferences() { final ObjectIdDictionary dict = new ObjectIdDictionary(); final Object a = new Object(); final Object b = new Object(); final Object c = new Object(); dict.associateId(a, "id a"); dict.associateId(b, "id b"); dict.associateId(c, "id c"); assertEquals("id a", dict.lookupId(a)); assertEquals("id b", dict.lookupId(b)); assertEquals("id c", dict.lookupId(c)); } public void testTreatsObjectsThatAreEqualButNotSameInstanceAsDifferentReference() { final ObjectIdDictionary dict = new ObjectIdDictionary(); final Integer a = new Integer(3); final Integer b = new Integer(3); dict.associateId(a, "id a"); dict.associateId(b, "id b"); assertEquals("id a", dict.lookupId(a)); assertEquals("id b", dict.lookupId(b)); } public void testEnforceSameSystemHashCodeForGCedObjects() throws NoSuchFieldException, IllegalAccessException { System.setProperty("xstream.debug", "true"); final Field invalidCounter = ObjectIdDictionary.class .getDeclaredField("invalidCounter"); invalidCounter.setAccessible(true); final ObjectIdDictionary dict = new ObjectIdDictionary(); invalidCounter.setInt(dict, 1); final StringBuffer memInfo = new StringBuffer("JVM: "); memInfo.append(System.getProperty("java.version")); memInfo.append("\nMemoryInfo:\n"); memInfo.append(memoryInfo()); memInfo.append('\n'); byte[] memReserve = new byte[1024 * 512]; Arrays.fill(memReserve, (byte)255); // prevent JVM optimization int oome = 0; int counter = 0; try { for (; invalidCounter.getInt(dict) != 0; ++counter) { try { final String s = new String("JUnit ") + counter; // enforce new object assertFalse("Failed in (" + counter + ")", dict.containsId(s)); dict.associateId(s, "X"); if (counter % 10000 == 9999) { forceGC(memInfo); } } catch (final OutOfMemoryError e) { memReserve = null; forceGC(memInfo); if ( ++oome == 5) { memInfo.append("Counter: "); memInfo.append(counter); memInfo.append("\nInvalid Counter: "); memInfo.append(invalidCounter.getInt(dict)); memInfo.append('\n'); System.out.println(memInfo); throw e; } memReserve = new byte[1024 * 512]; } } assertTrue("Dictionary did not shrink; " + counter + " distinct objects; " + dict.size() + " size; " + memInfo, dict.size() < 10); } catch (final ForceGCError error) { memInfo.append("Counter: "); memInfo.append(counter); memInfo.append("\nInvalid Counter: "); memInfo.append(invalidCounter.getInt(dict)); memInfo.append('\n'); System.out.println(memInfo); throw error; } finally { System.setProperty("xstream.debug", "false"); } } private void forceGC(final StringBuffer memInfo) { memInfo.append(memoryInfo()); memInfo.append('\n'); int i = 0; final SoftReference ref = new SoftReference(new Object()); for (int count = 0; ref.get() != null && count++ < 4;) { List memory = new ArrayList(); try { // fill up memory while (ref.get() != null) { memory.add(new byte[1024 * 16]); } } catch (final OutOfMemoryError error) { // expected } i = memory.size(); memory.clear(); memory = null; System.gc(); System.runFinalization(); try { Thread.sleep(1000); } catch (final InterruptedException e) { // ignore } } memInfo.append("Force GC, allocated blocks of 16KB: " + i); memInfo.append('\n'); if (ref.get() == null) { throw new ForceGCError("This JVM is not releasing memory!"); } } private String memoryInfo() { final Runtime runtime = Runtime.getRuntime(); final StringBuffer buffer = new StringBuffer("Memory: "); buffer.append(runtime.freeMemory()); buffer.append(" free / "); buffer.append(runtime.totalMemory()); buffer.append(" total / "); buffer.append(runtime.maxMemory()); buffer.append(" max"); return buffer.toString(); } private static class ForceGCError extends Error { public ForceGCError(final String msg) { super(msg); } } }
package gr.demokritos.iit.ydsapi.model; import java.util.HashSet; import java.util.Set; /** * accepted component types. * * @author George K. <gkiom@iit.demokritos.gr> */ public enum ComponentType { LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"), RESULT("result"), RESULTSET("resultset"); private final String type; private ComponentType(String type) { this.type = type; } public String getDecl() { return type; } public static final Set<String> ACCEPTED = new HashSet(); static { ACCEPTED.add(LINE.getDecl()); ACCEPTED.add(SCATTER.getDecl()); ACCEPTED.add(BUBBLE.getDecl()); ACCEPTED.add(PIE.getDecl()); ACCEPTED.add(BAR.getDecl()); ACCEPTED.add(TREE.getDecl()); ACCEPTED.add(MAP.getDecl()); ACCEPTED.add(GRID.getDecl()); ACCEPTED.add(RESULT.getDecl()); ACCEPTED.add(RESULTSET.getDecl()); } }
package com.levelup.bazquxforpalabre; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.ion.Ion; import com.koushikdutta.ion.Response; import com.levelup.palabre.api.ExtensionAccountInfo; import com.levelup.palabre.api.ExtensionUpdateStatus; import com.levelup.palabre.api.PalabreExtension; import com.levelup.palabre.api.datamapping.Article; import com.levelup.palabre.api.datamapping.Category; import com.levelup.palabre.api.datamapping.Source; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; public class BazquxExtension extends PalabreExtension { public static final String LATEST_ARTICLE_DATE = "LatestArticleDate"; public static final String TOR_CAT_SUBSCRIPTION = "tor/-/label/Subscription"; private static final String TAG = BazquxExtension.class.getSimpleName(); SharedPreferences sharedPref; @Override protected void onUpdateData() { sharedPref = PreferenceManager.getDefaultSharedPreferences(this); final String authKey = sharedPref.getString(SharedPreferenceKeys.AUTH, null); Log.d("TOR", "Palabre asked that we refresh our data! " + authKey); publishUpdateStatus(new ExtensionUpdateStatus().start()); // send information to Palabre for the progress bar publishUpdateStatus(new ExtensionUpdateStatus().progress(5)); // get user profile Ion.with(this).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String resultS) { Log.d("TOR", "user info " + resultS.toString()); JsonObject result = new JsonObject(); result = stringToJson(resultS); //Gson gson = new Gson(); //target2 = gson.fromJson(result, JsonObject.class); if (result != null) { Log.d("TOR", result.toString()); String username = result.get("userName").getAsString(); Log.d("TOR", "user name " + username); String email = result.get("userEmail").getAsString(); ExtensionAccountInfo account = new ExtensionAccountInfo(); account.accountName(username); account.accountEmail(email); publishAccountInfo(account); publishUpdateStatus(new ExtensionUpdateStatus().progress(10)); } } }); // get the categories/tags fetchCategories(this, authKey, new OnCategoryAndSourceRefreshed() { @Override public void onFinished() { fetchArticles(authKey, 0); } @Override public void onFailure(Exception e) { endService(e); } @Override public void onProgressChanged(int progress) { publishUpdateStatus(new ExtensionUpdateStatus().progress(progress)); } }); } public static void fetchCategories(final Context context, final String authKey, final OnCategoryAndSourceRefreshed listener) { final List<Category> previousCategories = Category.getAll(context); Ion.with(context).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String resultS) { JsonObject result = new JsonObject(); result = stringToJson(resultS); //Gson gson = new Gson(); //result = gson.fromJson(resultS, JsonObject.class); //Log.d("TOR", "user info " + resultS.toString()); if (result != null) { // We are getting the categories in an array JsonArray tags = result.get("tags").getAsJsonArray(); // create a list of categories so we can save them all after parsing them ArrayList<Category> categories = new ArrayList<Category>(); for (int i = 0; i < tags.size(); i++) { String id = null; try { id = tags.get(i).getAsJsonObject().get("id").getAsString(); } catch (NullPointerException e1) { if (listener != null) { listener.onFailure(e1); return; } } // we are getting the tags in this format: "user/-/label/Gaming" // So we need to split the string to extract a user friendly category name String[] splittedId = id.split("/"); String catName = splittedId[splittedId.length - 1]; if (id.equals("user/-/state/com.google/starred")) { continue; } Log.d("TOR", "Folder name: " + catName); // Category is a Palabre object Category category = new Category(); category.setUniqueId(id); category.setTitle(catName); // add it to the list categories.add(category); } if (listener != null) { listener.onProgressChanged(10); } // now save them using Palabre API. Category.multipleSave(context, categories); // remove the categories that the user might have deleted final List<Category> catsToRemove = new ArrayList<Category>(); for (int c = 0; c < previousCategories.size(); c++) { boolean found = false; for (Category newCats : categories) { if (newCats.getUniqueId().equals(previousCategories.get(c).getUniqueId())) { found = true; } } if (!found) { Log.d("TOR", "Found cat to remove: " + previousCategories.get(c).getTitle()); catsToRemove.add(previousCategories.get(c)); } } for (Category catToRemove : catsToRemove) { catToRemove.delete(context); } if (listener != null) { listener.onProgressChanged(20); } // now we can fetch the feed sources fetchSources(context, authKey, listener); } else { if (listener != null) { listener.onFailure(e); } } } }); } private static void fetchSources(final Context context, final String authKey, final OnCategoryAndSourceRefreshed listener) { final List<Category> categories = Category.getAll(context); final List<Source> previousSources = Source.getAll(context); Ion.with(context).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String resultS) { JsonObject result = new JsonObject(); result = stringToJson(resultS); //Gson gson = new Gson(); //result = gson.fromJson(resultS, JsonObject.class); if (result != null) { if (listener != null) { listener.onProgressChanged(25); } // create a list of sources that we will save once everything has been parsed ArrayList<Source> sources = new ArrayList<Source>(); JsonArray subscriptions = result.get("subscriptions").getAsJsonArray(); for (int i = 0; i < subscriptions.size(); i++) { String id = null; String title = null; String iconUrl = null; JsonArray subscribtionsCats = null; try { id = subscriptions.get(i).getAsJsonObject().get("id").getAsString(); title = subscriptions.get(i).getAsJsonObject().get("title").getAsString(); //iconUrl = subscriptions.get(i).getAsJsonObject().get("iconUrl").getAsString(); subscribtionsCats = subscriptions.get(i).getAsJsonObject().get("categories").getAsJsonArray(); } catch (NullPointerException e1) { if (listener != null) { listener.onFailure(e1); return; } } Source source = new Source(); source.setUniqueId(id); source.setTitle(title); source.setIconUrl(iconUrl); // assign source to existing categories for (int j = 0; j < subscribtionsCats.size(); j++) { String catId = subscribtionsCats.get(j).getAsJsonObject().get("id").getAsString(); // find the existing category and use it to associate the source with it for (Category cat : categories) { if (cat.getUniqueId().equals(catId)) { source.getCategories().add(cat); } } } // We might need to handle subscriptions without a categories, we will create a "Subscriptions" category in this case if (subscribtionsCats.size() == 0) { // there is no cat assigned, we will then create that cat (if needed) // and assign this source to it boolean requiredCatCreation = true; for (Category cat : categories) { if (cat.getUniqueId().equals(TOR_CAT_SUBSCRIPTION)) { source.getCategories().add(cat); requiredCatCreation = false; } } if (requiredCatCreation) { // create the cat Category category = new Category(); category.setUniqueId(TOR_CAT_SUBSCRIPTION); category.setTitle("Subscriptions"); category.save(context); source.getCategories().add(category); } } sources.add(source); } if (listener != null) { listener.onProgressChanged(35); } // ask Palabre to save them Source.multipleSave(context, sources); // remove the sources that the user might have deleted. Children Articles will automatically be removed as well. final List<Source> sourcesToRemove = new ArrayList<Source>(); for (int c = 0; c < previousSources.size(); c++) { boolean found = false; for (Source newSrc : sources) { if (newSrc.getUniqueId().equals(previousSources.get(c).getUniqueId())) { found = true; } } if (!found) { Log.d("TOR", "Found src to remove: " + previousSources.get(c).getTitle()); sourcesToRemove.add(previousSources.get(c)); } } for (Source src : sourcesToRemove) { src.delete(context); } if (listener != null) { listener.onProgressChanged(40); } // then fetch the articles if (listener != null) { listener.onFinished(); } } else { if (listener != null) { listener.onFailure(e); } } } }); } private void fetchArticles(final String authKey, final long continuationId) { if (BuildConfig.DEBUG) Log.d(TAG, "TimeTracking: fetchArticles"); // retrieve the sources so we can assign articles to sources (if applicable) final List<Source> sources = Source.getAll(this); // we will save the most recent article date in milliseconds, then store it // so later we can query the API for newer articles only, on a future refresh long latestArticleDate = sharedPref.getLong(LATEST_ARTICLE_DATE, 0); String query = "https: if (continuationId != 0) { // a continuation id means that the previous request had more data, and that we can query the continuation of our previous request query += "&c=" + continuationId; } if (latestArticleDate == 0) { // this is our first refresh, we are going to get articles newer than 3 days long firstDate = System.currentTimeMillis() - (TimeUnit.DAYS.toMillis(3)); query += "&ot=" + (firstDate/1000); } else { // we do an incremental refresh query += "&ot=" + (latestArticleDate/1000); } Ion.with(this).load(query) .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String resultS) { //Log.d("BAZ", "Fetch articles " + resultS.toString()); JsonObject result = new JsonObject(); result = stringToJson(resultS); //Gson gson = new Gson(); //result = gson.fromJson(resultS, JsonObject.class); if (result != null) { List<Article> allArticles = Article.getAll(BazquxExtension.this); if (BuildConfig.DEBUG) Log.d(TAG, "TimeTracking: request done"); publishUpdateStatus(new ExtensionUpdateStatus().progress(50)); // create a list of articles that we will save once everything has been parsed ArrayList<Article> articles = new ArrayList<Article>(); JsonArray items = result.get("items").getAsJsonArray(); for (int i = 0; i < items.size(); i++) { // FIXME: duplicated code here and in // starred items. // FIXMEs below apply to fetchSaved() too. String id = items.get(i).getAsJsonObject().get("id").getAsString(); long date = items.get(i).getAsJsonObject().get("crawlTimeMsec").getAsLong(); // FIXME: code below looks for incorrect ID // and has O(n^2) complexity. // Anyway it seems that Palabre doesn't // duplicates articles with the same ID. // boolean found = false; // for (Article article : allArticles) { // if (article.getUniqueId().equals(id) && article.getDate().getTime() == date) { // found = true; // break; // if (found) { // continue; // FIXME: // Why not // item = items.get(i).getAsJsonObject() // article.setTitle(item.get("title").as...) String summary = null; String title = null; String author = null; String link = null; String sourceUniqueId = null; try { summary = items.get(i).getAsJsonObject().get("summary").getAsJsonObject().get("content").getAsString(); title = items.get(i).getAsJsonObject().get("title").getAsString(); author = items.get(i).getAsJsonObject().get("author").getAsString(); if(items.get(i).getAsJsonObject().get("canonical").getAsJsonArray().size() != 0) { link = items.get(i).getAsJsonObject().get("canonical").getAsJsonArray().get(0).getAsJsonObject().get("href").getAsString(); } sourceUniqueId = items.get(i).getAsJsonObject().get("origin").getAsJsonObject().get("streamId").getAsString(); } catch (NullPointerException e1) { endService(e1); return; } //Ugly wya to convert id tag:google.com,2005:reader/item/base64 to only long id String modified = id.replaceAll("tag:google.com,2005:reader/item/", ""); Long decimal = Long.parseLong(modified, 16); Article article = new Article(); article.setUniqueId(Long.toString(decimal)); article.setTitle(title); article.setAuthor(author); article.setLinkUrl(link); article.setFullContent(summary); article.setDate(new Date(date)); // always keep the most recent article date for later use latestArticleDate = Math.max(latestArticleDate, date); // we need the Palabre internal id for the source boolean sourceIdFound = false; // FIXME: O(n^2). Ineffective when there are // many feeds. // Need HashMap of sources or something like this // for O(1) checking. for (Source source : sources) { if (source.getUniqueId().equals(sourceUniqueId)) { article.setSourceId(source.getId()); sourceIdFound = true; break; } } if (!sourceIdFound) continue; // find a picture within the article/summary using Jsoup. // Some API/Services provides the picture directly, but that's not the case here Document doc = Jsoup.parse(article.getFullContent()); String image = null; for (Element el : doc.select("img")) { //Log.d("TOR", "Image: " + el.attr("src")); // filter a few pictures that has not relation with the article if (!el.attr("src").contains("feeds.feedburner.com") && !el.attr("src").contains("feedsportal.com")) { // use the first one if (image == null) { image = el.attr("src"); } } } article.setImage(image); articles.add(article); } if (BuildConfig.DEBUG) Log.d(TAG, "TimeTracking: queries generated"); publishUpdateStatus(new ExtensionUpdateStatus().progress(70)); // Save them into Palabre Article.multipleSave(BazquxExtension.this, articles); if (BuildConfig.DEBUG) Log.d(TAG, "TimeTracking: saves finished"); publishUpdateStatus(new ExtensionUpdateStatus().progress(75)); // now save a reference to the latest article date, save it, so on next refresh we will start from this date sharedPref.edit().putLong(LATEST_ARTICLE_DATE, latestArticleDate).apply(); JsonElement continuationObject = result.get("continuation"); if (continuationObject != null) { // we can requery the continuation of our query Log.d("TOR", "Continuation Id detected, requery " + result.get("continuation").getAsLong()); long newContinuationId = result.get("continuation").getAsLong(); fetchArticles(authKey, newContinuationId); } else { Log.d("TOR", "No Continuation"); fetchSaved(authKey); } } else { endService(e); } } }); } private void endService(Exception e) { if (e != null) { Log.w(TAG, e.getMessage(), e); String errorString; if (e instanceof UnknownHostException) { errorString = getResources().getString(R.string.refresh_error_connection); } else { errorString = getResources().getString(R.string.refresh_error, "\n" + e.getMessage()); } publishUpdateStatus(new ExtensionUpdateStatus().fail(errorString)); } else { publishUpdateStatus(new ExtensionUpdateStatus().stop()); } } private void fetchSaved(final String authKey) { // retrieve the sources so we can assign articles to sources (if applicable) final List<Source> sources = Source.getAll(this); publishUpdateStatus(new ExtensionUpdateStatus().progress(77)); Ion.with(this).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String resultS) { JsonObject result = new JsonObject(); Gson gson = new Gson(); result = gson.fromJson(resultS, JsonObject.class); Log.d("TOR", "Starred " + resultS.toString()); if (result != null) { // create a list of articles that we will save once everything has been parsed ArrayList<Article> articles = new ArrayList<Article>(); JsonElement itemsElement = result.get("items"); if (itemsElement != null) { JsonArray items = result.get("items").getAsJsonArray(); for (int i = 0; i < items.size(); i++) { String id = null; String title = null; String author = null; String summary = null; String link = null; long date = 0; String sourceUniqueId = null; try { id = items.get(i).getAsJsonObject().get("id").getAsString(); title = items.get(i).getAsJsonObject().get("title").getAsString(); author = items.get(i).getAsJsonObject().get("author").getAsString(); summary = items.get(i).getAsJsonObject().get("summary").getAsJsonObject().get("content").getAsString(); // To do: check Canonical if(items.get(i).getAsJsonObject().get("canonical").getAsJsonArray().size() != 0) { link = items.get(i).getAsJsonObject().get("canonical").getAsJsonArray().get(0).getAsJsonObject().get("href").getAsString(); } date = items.get(i).getAsJsonObject().get("crawlTimeMsec").getAsLong(); if (items.get(i).getAsJsonObject().get("origin") != null) { sourceUniqueId = items.get(i).getAsJsonObject().get("origin").getAsJsonObject().get("streamId").getAsString(); } } catch (NullPointerException e1) { endService(e1); return; } //Ugly wya to convert id tag:google.com,2005:reader/item/base64 to only long id String modified = id.replaceAll("tag:google.com,2005:reader/item/", ""); Long decimal = Long.parseLong(modified, 16); Article starred = new Article(); starred.setUniqueId(Long.toString(decimal)); starred.setTitle(title); starred.setAuthor(author); starred.setLinkUrl(link); starred.setFullContent(summary); starred.setDate(new Date(date)); // this is how we mark them as starred in Palabre starred.setSaved(true); // we need the Palabre internal id for the source boolean sourceIdFound = false; for (Source source : sources) { if (source.getUniqueId().equals(sourceUniqueId)) { starred.setSourceId(source.getId()); sourceIdFound = true; break; } } if (!sourceIdFound) continue; // find a picture within the article/summary using Jsoup. // Some API/Services provides the picture directly, but that's not the case here Document doc = Jsoup.parse(starred.getFullContent()); String image = null; for (Element el : doc.select("img")) { //Log.d("TOR", "Image: " + el.attr("src")); // filter a few pictures that has not relation with the article if (!el.attr("src").contains("feeds.feedburner.com") && !el.attr("src").contains("feedsportal.com")) { // use the first one if (image == null) { image = el.attr("src"); } } } starred.setImage(image); articles.add(starred); } publishUpdateStatus(new ExtensionUpdateStatus().progress(82)); // Save them into Palabre Article.multipleSave(BazquxExtension.this, articles); } publishUpdateStatus(new ExtensionUpdateStatus().progress(85)); fetchReads(authKey); } else { endService(e); } } }); } private void fetchReads(final String authKey) { // we are going to query for the already read items, so if they are read // somewhere else (like on the old reader website), we can mark them as read local Log.d("Baz", "Fetching reads"); final List<Article> articles = Article.getAll(this); // FIXME: // Need to take in account that user can mark already read item // as unread. So it worth to take all ids. // FIXME: // Highly inneffectife O(n^2) algorithm as everywhere. // Need HashMap or something like it to store read state // and update articles state later. // we need to find the oldest article, and then we will ask Bazqux // for the read IDs since then. Then we will check if they are unread locally, and mark them as read in Palabre // Unfortunately the API does not have an API that could save us from doing so much processing, so we will have // to do a lot of iterations. long oldestArticle = System.currentTimeMillis(); for (Article article : articles) { oldestArticle = Math.min(oldestArticle, article.getDate().getTime()); } Log.d("Baz", "oldest article: "+ oldestArticle); Ion.with(this).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String resultS) { JsonObject result = new JsonObject(); Gson gson = new Gson(); result = gson.fromJson(resultS, JsonObject.class); if (result != null) { JsonArray items = result.get("itemRefs").getAsJsonArray(); for (int i = 0; i < items.size(); i++) { String uniqueId = items.get(i).getAsJsonObject().get("id").getAsString(); //Log.d("TOR", "Local Article " + items.get(i).getAsJsonObject().get("id").getAsString()); for (Article article : articles) { if (article.getUniqueId().contains(uniqueId) && !article.isRead()) { article.setRead(true); article.save(BazquxExtension.this); } } } endService(null); } else { endService(e); } } }); } @Override protected void onReadArticles(List<String> uniqueIdsList, boolean read) { // https://github.com/bazqux/api#updating-items Log.d("TOR", "Mark as read items"); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String authKey = sharedPref.getString(SharedPreferenceKeys.AUTH, null); String items = ""; for (String uniqueId : uniqueIdsList) { //Log.d("TOR", "Id: " + uniqueId); if (items.length() > 0) { // if there is more than one item, we need to append the other ids items += "&i="; } items += uniqueId; } // default action is to mark as read String action = "a"; if (!read) { // We need to mark as unread action = "r"; } Ion.with(this).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .setBodyParameter(action, "user/-/state/com.google/read") .setBodyParameter("i", items) .asString() .withResponse() .setCallback(new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception e, Response<String> result) { try { Log.w("TOR", "Sending mark as read/unread: " + result.getHeaders().code()); } catch (Exception e1) { } } }); } @Override protected void onReadArticlesBefore(String type, String uniqueId, long timestamp) { if (BuildConfig.DEBUG) Log.d(TAG, "onReadArticlesBefore for: " + type + " before " + new Date(timestamp) + " with uniqueId" + uniqueId); if (type.equals("all")) { uniqueId = "user%2F-%2Fstate%2Fcom.google%2Freading-list"; } sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String authKey = sharedPref.getString(SharedPreferenceKeys.AUTH, null); final long timestampNs = timestamp * 1000; Ion.with(this).load("https: .setHeader("Authorization", "GoogleLogin auth=" + authKey) .setHeader("User-Agent", "Palabre") .setBodyParameter("s", uniqueId) .setBodyParameter("ts", String.valueOf(timestampNs)) .asString() .withResponse() .setCallback(new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception e, Response<String> result) { try { Log.w("TOR", "Sending mark as read before: " + result.getHeaders().code() +" => "+ result.getResult()); } catch (Exception e1) { } } }); } @Override protected void onSavedArticles(List<String> uniqueIdsList, boolean saved) { // https://github.com/bazqux/api#updating-items Log.d("TOR", "Mark as saved items"); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String authKey = sharedPref.getString(SharedPreferenceKeys.AUTH, null); String items = ""; for (String uniqueId : uniqueIdsList) { if (items.length() > 0) { // if there is more than one item, we need to append the other ids items += "&i="; } items += uniqueId; } // default action is to mark as starred String action = "a"; if (!saved) { // We need to mark as unstarred action = "r"; } Ion.with(this).load("https: .setHeader("Authorization", " GoogleLogin auth="+authKey) .setHeader("User-Agent", "Palabre") .setBodyParameter(action, "user/-/state/com.google/starred") .setBodyParameter("i", items) .asString() .withResponse() .setCallback(new FutureCallback<Response<String>>() { @Override public void onCompleted(Exception e, Response<String> result) { Log.w("TOR", "Sending mark as starred/unstarred: " + result.getHeaders().code()); } }); } public interface OnCategoryAndSourceRefreshed { void onFinished(); void onFailure(Exception e); void onProgressChanged(int progress); } private static JsonObject stringToJson (String s){ JsonObject j = new JsonObject(); Gson gson = new Gson(); j = gson.fromJson(s, JsonObject.class); return j; } }
package de.comeight.crystallogy.particles; import java.util.LinkedList; import javax.annotation.Nonnull; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ParticleHandler { private static LinkedList<BaseParticle> particleList = new LinkedList<BaseParticle>(); @SubscribeEvent public void stitcherEventPre(TextureStitchEvent.Pre e) { registerParticleTextures(e); } public void registerParticles(){ registerParticle(new ParticleA()); registerParticle(new ParticleB()); registerParticle(new ParticleC()); registerParticle(new ParticleD()); registerParticle(new ParticleE()); registerParticle(new ParticleF()); registerParticle(new ParticleN_Color()); registerParticle(new ParticleLight()); registerParticle(new ParticleInfusion()); registerParticle(new ParticleInfuserBlockStatus()); registerParticle(new ParticleEnderon()); registerParticle(new ParticleDebug()); } public void registerParticleTextures(TextureStitchEvent.Pre event){ ResourceLocation rL; for (BaseParticle baseParticle : particleList) { rL = baseParticle.rL; if(rL != null){ event.getMap().registerSprite(rL); } } } public static void registerParticle(@Nonnull BaseParticle p){ particleList.add(p); } public static BaseParticle findParticle(String id){ for (BaseParticle baseParticle : particleList) { if(baseParticle.id.equals(id)){ return baseParticle; } } return null; } public void preInit() { registerParticles(); } public void init() { } public void postInit() { } }
package ch.severinkaderli.snake; import java.awt.Graphics; import java.util.ArrayList; import java.util.List; /** * * @author Severin Kaderli */ public class Snake { /** * Die Richtung in die sich die Schlange momentan bewegt. */ //private Direction direction = Direction.LEFT; /** * Breite und Hhe der einzelnen Schlangenteile. */ private final int BODY_SIZE = 10; /** * Liste, die die einzelnen Teile der Schlange enthlt */ public List<SnakePart> body = new ArrayList<SnakePart>(); public SnakePart head; /** * Game Objekt zu welchem die Schlange dazu gehrt. */ private Game game; /** * * @param x * @param y * @param width * @param height */ public Snake(int x, int y, Game game) { //Add first (head) part head = new SnakePart(x, y, BODY_SIZE, BODY_SIZE, Direction.LEFT); body.add(new SnakePart(x+BODY_SIZE, y, BODY_SIZE, BODY_SIZE, Direction.LEFT)); body.add(new SnakePart(x+BODY_SIZE*2, y, BODY_SIZE, BODY_SIZE, Direction.LEFT)); body.add(new SnakePart(x+BODY_SIZE*3, y, BODY_SIZE, BODY_SIZE, Direction.LEFT)); body.add(new SnakePart(x+BODY_SIZE*4, y, BODY_SIZE, BODY_SIZE, Direction.LEFT)); this.game = game; } /** * Zeichnet die Schlange auf das Feld. */ public void draw(Graphics g) { head.draw(g); body.forEach(part -> part.draw(g)); } /** * Setzt die aktuelle Richtung der Schlange. * * @param direction */ public void changeDirection(Direction direction) { //Check if the direction is possible //Todo: add correct checking constraints if(!(head.direction == Direction.LEFT && direction == Direction.RIGHT) && !(head.direction == Direction.RIGHT && direction == Direction.LEFT) && !(head.direction == Direction.UP && direction == Direction.DOWN) && !(head.direction == Direction.DOWN && direction == Direction.UP)) { head.direction = direction; } } /** * Bewegt die Schlange ber das Feld * * @param steps */ public void move(int stepSize) { SnakePart oldHead = head; head = body.remove(body.size()-1); body.add(0, oldHead); head.direction = oldHead.direction; switch(head.direction) { default: case LEFT: head.position.x = oldHead.position.x - BODY_SIZE; head.position.y = oldHead.position.y; break; case RIGHT: head.position.x = oldHead.position.x + BODY_SIZE; head.position.y = oldHead.position.y; break; case UP: head.position.x = oldHead.position.x; head.position.y = oldHead.position.y - BODY_SIZE; break; case DOWN: head.position.x = oldHead.position.x; head.position.y = oldHead.position.y + BODY_SIZE; break; } } /** * berprft Kollisionen */ public void checkCollision() { //Collision with diamonds game.getDiamonds().forEach((diamond) -> { if (diamond.isAlive) { if (head.position.intersects(diamond.position)) { game.setScore(game.getScore() + diamond.value); // Remove diamond diamond.destroy(); } } }); //Collision with itself body.forEach((part) -> { if(head.position.intersects(part.position)) { game.end(); System.out.println("Touch itself"); } }); //Collision with the border if(!head.position.intersects(game.border.position)) { game.end(); System.out.println("Out of area"); } } }
package com.littleinc.orm_benchmark.realm; import android.content.Context; import android.util.Log; import com.littleinc.orm_benchmark.BenchmarkExecutable; import com.littleinc.orm_benchmark.util.Util; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Random; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmQuery; import io.realm.RealmResults; import static com.littleinc.orm_benchmark.util.Util.getRandomString; public class RealmExecutor implements BenchmarkExecutable { private static final String TAG = "RealmExecutor"; //private DataBaseHelper mHelper; private Context mContext; @Override public void init(Context context, boolean useInMemoryDb) { mContext = context; // Realm.getInstance(context); } @Override public String getOrmName() { return "Realm"; } @Override public long createDbStructure() throws SQLException { return 0; } @Override public long writeWholeData() throws SQLException { Random random = new Random(); List<User> users = new ArrayList<User>(NUM_USER_INSERTS); for (int i = 0; i < NUM_USER_INSERTS; i++) { User newUser = new User(); newUser.setId(i); newUser.setmLastName(getRandomString(10)); newUser.setmFirstName(getRandomString(10)); users.add(newUser); } List<Message> messages = new ArrayList<Message>(NUM_MESSAGE_INSERTS); for (int i = 0; i < NUM_MESSAGE_INSERTS; i++) { Message newMessage = new Message(); newMessage.setId(i); newMessage.setCommandId(i); newMessage.setSortedBy(System.nanoTime()); newMessage.setContent(Util.getRandomString(100)); newMessage.setClientId(System.currentTimeMillis()); newMessage .setSenderId(Math.round(Math.random() * NUM_USER_INSERTS)); newMessage .setChannelId(Math.round(Math.random() * NUM_USER_INSERTS)); newMessage.setCreatedAt((int) (System.currentTimeMillis() / 1000L)); messages.add(newMessage); } RealmConfiguration realmConfig = new RealmConfiguration.Builder(mContext).build(); // Open the Realm for the UI thread. Realm realm = Realm.getInstance(realmConfig); long start = System.nanoTime(); realm.beginTransaction(); String userLog; long messageStart; try { for(User newUser : users) { realm.insert(newUser); } userLog = "Done, wrote " + NUM_USER_INSERTS + " users" + (System.nanoTime() - start); messageStart = System.nanoTime(); for(Message message : messages) { realm.insert(message); } } finally { realm.commitTransaction(); } long totalTime = System.nanoTime() - start; realm.close(); Log.d(TAG, userLog); Log.d(TAG, "Done, wrote " + NUM_MESSAGE_INSERTS + " messages" + (System.nanoTime() - messageStart)); return totalTime; } @Override public long readWholeData() throws SQLException { long start = System.nanoTime(); RealmConfiguration realmConfig = new RealmConfiguration.Builder(mContext).build(); Realm realm = Realm.getInstance(realmConfig); RealmQuery<User> userQuery = realm.where(User.class); RealmResults<User> userResults = userQuery.findAll(); for(User user : userResults) { int id = user.getId(); String first = user.getmFirstName(); String last = user.getmLastName(); } String userLog = "Read " + NUM_USER_INSERTS + " users in " + (System.nanoTime() - start); long messageStart = System.nanoTime(); RealmQuery <Message> messageQuery = realm.where(Message.class); RealmResults<Message> messageResults =messageQuery.findAll(); for(Message message : messageResults) { int id = message.getId(); long channel = message.getChannelId(); long client = message.getClientId(); long command = message.getCommandId(); String content = message.getContent(); int created = message.getCreatedAt(); long sender = message.getSenderId(); double sorted = message.getSortedBy(); } long totalTime = System.nanoTime() - start; realm.close(); Log.d(TAG, userLog); Log.d(TAG, "Read " + NUM_MESSAGE_INSERTS + " messages in " + (System.nanoTime() - messageStart)); return totalTime; } @Override public long dropDb() throws SQLException { long start = System.nanoTime(); RealmConfiguration realmConfig = new RealmConfiguration.Builder(mContext).build(); Realm realm = Realm.getInstance(realmConfig); realm.beginTransaction(); try { realm.deleteAll(); } finally { realm.commitTransaction(); } realm.close(); return System.nanoTime() - start; } }
package devopsdistilled.operp.client.items.views; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.inject.Inject; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.SubTaskPane; import devopsdistilled.operp.client.items.controllers.CreateItemPaneController; import devopsdistilled.operp.client.items.models.observers.BrandModelObserver; import devopsdistilled.operp.client.items.models.observers.CreateItemPaneModelObserver; import devopsdistilled.operp.client.items.models.observers.ProductModelObserver; import devopsdistilled.operp.server.data.entity.items.Brand; import devopsdistilled.operp.server.data.entity.items.Item; import devopsdistilled.operp.server.data.entity.items.Product; public class CreateItemPane extends SubTaskPane implements CreateItemPaneModelObserver, ProductModelObserver, BrandModelObserver { @Inject private CreateItemPaneController controller; private final JPanel pane; private final JTextField itemNameField; private final JTextField priceField; private final JComboBox<Brand> comboBrands; private final JComboBox<Product> comboProducts; @Override public void init() { super.init(); } public CreateItemPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[][][grow][]", "[][][][][]")); JLabel lblProductName = new JLabel("Product Name"); pane.add(lblProductName, "cell 0 0,alignx trailing"); comboProducts = new JComboBox<Product>(); pane.add(comboProducts, "flowx,cell 2 0,growx"); JLabel lblBrandName = new JLabel("Brand Name"); pane.add(lblBrandName, "cell 0 1,alignx trailing"); comboBrands = new JComboBox<Brand>(); pane.add(comboBrands, "flowx,cell 2 1,growx"); JLabel lblItemId = new JLabel("Item Name"); pane.add(lblItemId, "cell 0 2,alignx trailing"); itemNameField = new JTextField(); pane.add(itemNameField, "cell 2 2,growx"); itemNameField.setColumns(10); JLabel lblPrice = new JLabel("Price"); pane.add(lblPrice, "cell 0 3,alignx trailing"); priceField = new JTextField(); pane.add(priceField, "cell 2 3,growx"); priceField.setColumns(10); JButton btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); pane.add(btnCancel, "flowx,cell 2 4"); JButton btnSave = new JButton("Create"); btnSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Item item = new Item(); Brand brand = (Brand) comboBrands.getSelectedItem(); Product product = (Product) comboProducts.getSelectedItem(); item.setBrand(brand); item.setProduct(product); } }); pane.add(btnSave, "cell 2 4"); JButton btnNewProduct = new JButton("New Product"); pane.add(btnNewProduct, "cell 2 0"); JButton btnNewBrand = new JButton("New Brand"); btnNewBrand.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); pane.add(btnNewBrand, "cell 2 1"); } @Override public JComponent getPane() { return pane; } @Override public void updateBrands(List<Brand> brands) { comboBrands.removeAllItems(); for (Brand brand : brands) { comboBrands.addItem(brand); } } @Override public void updateProducts(List<Product> products) { comboProducts.removeAllItems(); for (Product product : products) { comboProducts.addItem(product); } } }
package org.epics.pvmanager; /** * Groups all the parameters required to add a writer to a ChannelHandler. * * @author carcassi */ public class ChannelHandlerWriteSubscription { /** * Creates a new subscription. * * @param cache the cache where to read the value from * @param exceptionWriteFunction the write function to notify to process errors * @param connectionWriteFunction the write function to notify for connection updates */ public ChannelHandlerWriteSubscription(WriteCache<?> cache, WriteFunction<Exception> exceptionWriteFunction, WriteFunction<Boolean> connectionWriteFunction) { this.cache = cache; this.exceptionWriteFunction = exceptionWriteFunction; this.connectionWriteFunction = connectionWriteFunction; } private final WriteCache<?> cache; private final WriteFunction<Exception> exceptionWriteFunction; private final WriteFunction<Boolean> connectionWriteFunction; /** * The cache to hold the value to write. * * @return the write cache */ public WriteCache<?> getWriteCache() { return cache; } /** * The write function for connection/disconnection errors. * * @return the write function; never null */ public WriteFunction<Exception> getExceptionWriteFunction() { return exceptionWriteFunction; } /** * The write function for the connection flag. * * @return the write function; never null */ public WriteFunction<Boolean> getConnectionWriteFunction() { return connectionWriteFunction; } @Override public int hashCode() { int hash = 3; hash = 11 * hash + (this.cache != null ? this.cache.hashCode() : 0); hash = 11 * hash + (this.exceptionWriteFunction != null ? this.exceptionWriteFunction.hashCode() : 0); hash = 11 * hash + (this.connectionWriteFunction != null ? this.connectionWriteFunction.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChannelHandlerWriteSubscription other = (ChannelHandlerWriteSubscription) obj; if (this.cache != other.cache && (this.cache == null || !this.cache.equals(other.cache))) { return false; } if (this.exceptionWriteFunction != other.exceptionWriteFunction && (this.exceptionWriteFunction == null || !this.exceptionWriteFunction.equals(other.exceptionWriteFunction))) { return false; } if (this.connectionWriteFunction != other.connectionWriteFunction && (this.connectionWriteFunction == null || !this.connectionWriteFunction.equals(other.connectionWriteFunction))) { return false; } return true; } }
package nisrulz.github.example.usinglitho; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.LithoView; import com.facebook.litho.widget.Text; import static android.graphics.Typeface.BOLD; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ComponentContext context = new ComponentContext(this); final Component component = Text.create(context) .text("Hello World!") .textColor(Color.BLUE) .textSizeDip(40) .textStyle(BOLD) .build(); setContentView(LithoView.create(context, component)); } }
package edu.wustl.catissuecore.bizlogic; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import edu.wustl.catissuecore.domain.AbstractSpecimen; import edu.wustl.catissuecore.domain.CheckInCheckOutEventParameter; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.DisposalEventParameters; import edu.wustl.catissuecore.domain.EmbeddedEventParameters; import edu.wustl.catissuecore.domain.FixedEventParameters; import edu.wustl.catissuecore.domain.FrozenEventParameters; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Site; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.SpecimenEventParameters; import edu.wustl.catissuecore.domain.SpecimenPosition; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.domain.TissueSpecimenReviewEventParameters; import edu.wustl.catissuecore.domain.TransferEventParameters; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.ApiSearchUtil; import edu.wustl.catissuecore.util.CatissueCoreCacheManager; import edu.wustl.catissuecore.util.Position; import edu.wustl.catissuecore.util.SpecimenUtil; import edu.wustl.catissuecore.util.StorageContainerUtil; import edu.wustl.catissuecore.util.global.AppUtility; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.exception.ApplicationException; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.exception.ErrorKey; import edu.wustl.common.factory.AbstractFactoryConfig; import edu.wustl.common.factory.IFactory; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.CommonUtilities; import edu.wustl.common.util.global.Status; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; import edu.wustl.dao.DAO; import edu.wustl.dao.JDBCDAO; import edu.wustl.dao.QueryWhereClause; import edu.wustl.dao.condition.EqualClause; import edu.wustl.dao.condition.NotEqualClause; import edu.wustl.dao.exception.DAOException; import edu.wustl.dao.util.HibernateMetaData; import edu.wustl.security.exception.UserNotAuthorizedException; /** * @author mandar_deshmukh * This class contains the Business Logic for all EventParameters Classes. * This will be the class which will be used for data transactions of the EventParameters. */ public class SpecimenEventParametersBizLogic extends CatissueDefaultBizLogic { /** * Logger object. */ private static final Logger LOGGER = Logger .getCommonLogger(SpecimenEventParametersBizLogic.class); /** * storageContainerIds. */ private HashSet<String> storageContainerIds = new HashSet<String>(); /** * Saves the FrozenEventParameters object in the database. * @param obj The FrozenEventParameters object to be saved. * @param dao DAO Object * @param sessionDataBean SessionDataBean object * @throws BizLogicException throws BizLogicException. */ @Override protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws BizLogicException { final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory(); final NewSpecimenBizLogic newSpecimenBizLogic = (NewSpecimenBizLogic) factory .getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); final List specimenIds = new ArrayList(); if (obj instanceof List) { final List eventObjectsList = (List) obj; for (int i = 0; i < eventObjectsList.size(); i++) { specimenIds.add(((SpecimenEventParameters) eventObjectsList.get(i)).getSpecimen() .getId()); } for (int i = 0; i < eventObjectsList.size(); i++) { this.insertEvent(eventObjectsList.get(i), dao, sessionDataBean, newSpecimenBizLogic, specimenIds); } } else { this.insertEvent(obj, dao, sessionDataBean, newSpecimenBizLogic, specimenIds); } } /** * @param obj - Object. * @param dao - DAO object. * @param sessionDataBean - SessionDataBean object * @param newSpecimenBizLogic - NewSpecimenBizLogic object * @param specimenIds - List of specimenIds * @throws BizLogicException * @throws ApplicationException */ private void insertEvent(Object obj, DAO dao, SessionDataBean sessionDataBean, NewSpecimenBizLogic newSpecimenBizLogic, List specimenIds) throws BizLogicException { try { SpecimenEventParameters specimenEvent = (SpecimenEventParameters) obj; checkStatusAndGetUserId(specimenEvent, dao); // Ashish - 6/6/07 - performance improvement Object specimenObject = null; specimenObject = retrieveSpecimenLabelName(dao, specimenEvent); final Specimen specimen = (Specimen) specimenObject; // check for closed Specimen if (specimenEvent instanceof DisposalEventParameters) { this.checkStatus(dao, specimen, Constants.DISPOSAL_EVENT_PARAMETERS); } else { this.checkStatus(dao, specimen, Constants.SPECIMEN); } if(Status.ACTIVITY_STATUS_DISABLED.getStatus().equals(specimen.getActivityStatus())) { throw this.getBizLogicException(null, "error.object.disabled", "Specimen"); } if (specimen != null) { specimenEvent.setSpecimen(specimen); if (specimenEvent instanceof TransferEventParameters) { final TransferEventParameters transferEvent = (TransferEventParameters) specimenEvent; StorageContainer storageContainerObj = new StorageContainer(); List stNamelist = null; final String sourceObjectName = StorageContainer.class.getName(); String[] selectColumnName = null; storageContainerObj = transferEvent.getToStorageContainer(); if (storageContainerObj != null && (storageContainerObj.getId() != null || storageContainerObj .getName() != null)) { if (storageContainerObj.getId() == null) { //storageContainerObj.setId(storageContainerObj.getId()); selectColumnName = new String[]{"id"}; final QueryWhereClause queryWhereClause = new QueryWhereClause( sourceObjectName); queryWhereClause.addCondition(new EqualClause("name", transferEvent.getToStorageContainer().getName())); stNamelist = dao.retrieve(sourceObjectName, selectColumnName, queryWhereClause); if (!stNamelist.isEmpty()) { storageContainerObj.setId((Long) (stNamelist.get(0))); } } else { selectColumnName = new String[]{"name"}; final QueryWhereClause queryWhereClause = new QueryWhereClause( sourceObjectName); queryWhereClause.addCondition(new EqualClause("id", transferEvent.getToStorageContainer().getId())); stNamelist = dao.retrieve(sourceObjectName, selectColumnName, queryWhereClause); if (!stNamelist.isEmpty()) { storageContainerObj.setName((String) stNamelist.get(0)); } } // check for closed StorageContainer this.checkStatus(dao, storageContainerObj, "Storage Container"); final IFactory factory = AbstractFactoryConfig.getInstance() .getBizLogicFactory(); final StorageContainerBizLogic storageContainerBizLogic = (StorageContainerBizLogic) factory .getBizLogic(Constants.STORAGE_CONTAINER_FORM_ID); final String contId = storageContainerObj.getId().toString(); if(0==transferEvent.getToPositionDimensionOne() || 0==transferEvent.getToPositionDimensionTwo()) { Position position; try { position = StorageContainerUtil.getFirstAvailablePositionsInContainer(storageContainerObj, storageContainerIds, dao, transferEvent.getToPositionDimensionOne(), transferEvent.getToPositionDimensionTwo()); transferEvent.setToPositionDimensionOne(position.getXPos()); transferEvent.setToPositionDimensionTwo(position.getYPos()); } catch (ApplicationException e) { this.LOGGER.error(e.getMessage(), e); throw this .getBizLogicException(e, e.getErrorKeyName(), e.getMsgValues()); } } final String posOne = transferEvent.getToPositionDimensionOne() .toString(); final String posTwo = transferEvent.getToPositionDimensionTwo() .toString(); storageContainerBizLogic.checkContainer(dao, StorageContainerUtil .setparameterList(contId, posOne, posTwo, false), sessionDataBean, null); final SpecimenCollectionGroup scg = (SpecimenCollectionGroup) this .retrieveAttribute(dao, Specimen.class, specimen.getId(), "specimenCollectionGroup"); specimen.setSpecimenCollectionGroup(scg); newSpecimenBizLogic.chkContainerValidForSpecimen(storageContainerObj, specimen, dao); } else { storageContainerObj = null; } SpecimenPosition specimenPosition = specimen.getSpecimenPosition(); if (specimenPosition == null) { // trasfering from virtual location specimenPosition = new SpecimenPosition(); specimenPosition.setSpecimen(specimen); specimen.setSpecimenPosition(specimenPosition); } specimenPosition.setStorageContainer(storageContainerObj); specimenPosition.setPositionDimensionOne(transferEvent .getToPositionDimensionOne()); specimenPosition.setPositionDimensionTwo(transferEvent .getToPositionDimensionTwo()); if(storageContainerObj!=null) { StorageContainerUtil.setContainerPositionAsString(storageContainerObj.getName(), transferEvent .getToPositionDimensionOne(), transferEvent .getToPositionDimensionTwo(), specimenPosition); } if(storageContainerObj==null) { dao.delete(specimenPosition); specimen.setSpecimenPosition(null); } dao.update(specimen,null); transferEvent.setToStorageContainer(storageContainerObj); } if (specimenEvent instanceof DisposalEventParameters) { final DisposalEventParameters disposalEventParameters = (DisposalEventParameters) specimenEvent; if (disposalEventParameters.getActivityStatus().equals( Status.ACTIVITY_STATUS_DISABLED.getStatus())) { this.disableSubSpecimens(dao, specimen.getId().toString(), specimenIds); } final SpecimenPosition prevPosition = specimen.getSpecimenPosition(); specimen.setSpecimenPosition(null); specimen.setIsAvailable(Boolean.FALSE); specimen.setActivityStatus(disposalEventParameters.getActivityStatus()); dao.update(specimen); if (prevPosition != null) { dao.delete(prevPosition); } } } specimen.getSpecimenEventCollection().add(specimenEvent); specimenEvent.doRoundOff(); dao.insert(specimenEvent); } catch (final DAOException daoExp) { this.LOGGER.error(daoExp.getMessage(), daoExp); throw this .getBizLogicException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); } } /** * Retrieve specimen by label name. * @param dao DAO * @param specimenEventParametersObject SpecimenEventParameters * @return Object * @throws DAOException DAOException * @throws BizLogicException BizLogicException */ private Object retrieveSpecimenLabelName(DAO dao, SpecimenEventParameters specimenEventParametersObject) throws DAOException, BizLogicException { Object specimenObject = null; if (specimenEventParametersObject.getSpecimen().getId() != null) { specimenObject = dao.retrieveById(Specimen.class.getName(), specimenEventParametersObject.getSpecimen().getId()); } else if (specimenEventParametersObject.getSpecimen().getLabel() != null && specimenEventParametersObject.getSpecimen().getLabel().length() > 0) { String column = "label"; List list = dao.retrieve(Specimen.class.getName(), column, specimenEventParametersObject .getSpecimen().getLabel()); if (list.isEmpty()) { throw this.getBizLogicException(null, "invalid.label", specimenEventParametersObject.getSpecimen().getLabel()); } else { specimenObject = list.get(0); } } else if (specimenEventParametersObject.getSpecimen() instanceof Specimen && ((Specimen)specimenEventParametersObject.getSpecimen()).getBarcode() != null && ((Specimen)specimenEventParametersObject.getSpecimen()).getBarcode().length() > 0) { final Specimen specimen= (Specimen) specimenEventParametersObject.getSpecimen(); String column = "barcode"; List list = dao.retrieve(Specimen.class.getName(), column, specimen.getBarcode()); if (list.isEmpty()) { throw this.getBizLogicException(null, "invalid.barcode", specimen.getBarcode()); } else { specimenObject = list.get(0); } } return specimenObject; } /** * Check Status And Get UserId. * @param specimenEventParameter SpecimenEventParameters * @param dao DAO * @throws DAOException DAOException * @throws BizLogicException BizLogicException */ private void checkStatusAndGetUserId(SpecimenEventParameters specimenEventParameter, DAO dao) throws DAOException, BizLogicException { List list = null; String message = ""; if (specimenEventParameter.getUser().getId() != null) { list = dao.executeQuery("select id,activityStatus from edu.wustl.catissuecore.domain.User where id="+specimenEventParameter.getUser() .getId()); message = ApplicationProperties.getValue("app.UserID"); } else if (specimenEventParameter.getUser().getLoginName() != null || specimenEventParameter.getUser().getLoginName().length() > 0) { list = dao.executeQuery("select id,activityStatus from edu.wustl.catissuecore.domain.User where loginName='"+specimenEventParameter.getUser() .getLoginName()+"'"); message = ApplicationProperties.getValue("user.loginName"); } if(list!=null&&!list.isEmpty()) { Object[] object = (Object[])list.get(0); final User user = new User(); user.setId((Long)object[0]); user.setActivityStatus((String)object[1]); // check for closed User this.checkStatus(dao, user, "User"); specimenEventParameter.setUser(user); } else { throw this.getBizLogicException(null, "errors.item.forboformat", message); } } /** * Method overridden from DefaultBizLogic.java. This method checks for the specimens status * whether it is closed. If the event is disposal only then it does not throws exception. * @param dao DAo object. * @param specimen Specimen object on which event is happened. * @param objectType for knowing which event is happened. * @throws BizLogicException DAO Exception. */ protected void checkStatus(DAO dao, Specimen specimen, String objectType) throws BizLogicException { if (specimen != null) { final Long identifier = specimen.getId(); if (identifier != null) { final String className = specimen.getClass().getName(); String activityStatus = specimen.getActivityStatus(); if (activityStatus == null) { activityStatus = this.getActivityStatus(dao, className, identifier); } if (Status.ACTIVITY_STATUS_CLOSED.toString().equals(activityStatus) && (!Constants.DISPOSAL_EVENT_PARAMETERS.equals(objectType))) { throw this.getBizLogicException(null, "error.object.closed", objectType); } } } } /** * calling post insert of parent class * @param dao DAO Object * @param sessionDataBean SessionDataBean object * @param obj Domain object */ public void postInsert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws BizLogicException { super.postInsert(obj, dao, sessionDataBean); } /** * Updates the persistent object in the database. * @param dao - DAO object * @param obj The object to be updated. * @param oldObj - Object * @param sessionDataBean The session in which the object is saved. * @throws BizLogicException throws BizLogicException */ protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws BizLogicException { try { final SpecimenEventParameters specimenEventParameters = (SpecimenEventParameters) obj; final SpecimenEventParameters oldSpecimenEventParameters = (SpecimenEventParameters) oldObj; if (!specimenEventParameters.getUser().getId().equals( oldSpecimenEventParameters.getUser().getId())) { this.checkStatus(dao, specimenEventParameters.getUser(), "User"); } if (specimenEventParameters instanceof DisposalEventParameters) { updateDisposalEvent(dao, (DisposalEventParameters) specimenEventParameters); } specimenEventParameters.doRoundOff(); //Update registration dao.update(specimenEventParameters, oldSpecimenEventParameters); } catch (final DAOException daoExption) { this.LOGGER.error(daoExption.getMessage(), daoExption); throw this.getBizLogicException(daoExption, daoExption.getErrorKeyName(), daoExption .getMsgValues()); } } /** * @param dao * @param specimenEventParameters * @param specimen * @param specimenIds * @throws BizLogicException * @throws DAOException */ private void updateDisposalEvent(DAO dao, final DisposalEventParameters disposalEventParameters) throws BizLogicException, DAOException { final Specimen specimen = (Specimen) HibernateMetaData .getProxyObjectImpl(disposalEventParameters.getSpecimen()); final SpecimenPosition prevPosition = specimen.getSpecimenPosition(); specimen.setSpecimenPosition(null); specimen.setIsAvailable(Boolean.FALSE); specimen.setActivityStatus(((DisposalEventParameters) disposalEventParameters) .getActivityStatus()); //Update Specimen if (disposalEventParameters.getActivityStatus().equals( Status.ACTIVITY_STATUS_DISABLED.toString())) { final List specimenIds = new ArrayList(); this.disableSubSpecimens(dao, specimen.getId().toString(), specimenIds); } dao.update(specimen); if (prevPosition != null) { dao.delete(prevPosition); } } /** * Overriding the parent class's method to validate the enumerated attribute values. * @param obj Domain object * @param dao DAO object * @param operation operation add/edit * */ protected boolean validate(Object obj, DAO dao, String operation) throws BizLogicException { // For bulk operations if (obj instanceof List) { final List events = (List) obj; //This map maintains the current event no being added per container final Map containerEventNumberMap = new HashMap(); SpecimenEventParameters specimenEventParameters = null; //This is the event number corresponding to the current container. //This number is required to get the next location in the container that should be available Integer eventNumber = null; //Bug 15392 Integer pos1 = null; Integer pos2 = null; for (int i = 0; i < events.size(); i++) { specimenEventParameters = (SpecimenEventParameters) events.get(i); if (specimenEventParameters instanceof TransferEventParameters) { final TransferEventParameters trEvent = (TransferEventParameters) specimenEventParameters; if(trEvent.getToStorageContainer()!=null) { //Bug 15392 pos1 = trEvent.getToPositionDimensionOne(); pos2 = trEvent.getToPositionDimensionTwo(); if(((pos1 == null || pos2 == null) && i!=0)) { if(((TransferEventParameters)(events.get(i-1))).getToStorageContainer()!=null) { String prevToStrContName = ((TransferEventParameters)(events.get(i-1))). getToStorageContainer().getName(); String toStrContName = trEvent.getToStorageContainer().getName(); if((!Validator.isEmpty(prevToStrContName)) && (!Validator.isEmpty(toStrContName)) && (toStrContName.equals(prevToStrContName))) { pos1 = ((TransferEventParameters)(events.get(i-1))).getToPositionDimensionOne(); pos2 = ((TransferEventParameters)(events.get(i-1))).getToPositionDimensionTwo(); } } } eventNumber = (Integer) containerEventNumberMap.get(trEvent .getToStorageContainer().getName()); if (eventNumber == null) { eventNumber = Integer.valueOf(0); } containerEventNumberMap.put(trEvent.getToStorageContainer().getName(), Integer .valueOf(eventNumber.intValue() + 1)); } } else { if (eventNumber == null) { eventNumber = Integer.valueOf(0); } else { eventNumber++; } } boolean isValidEvent = true; //bug 15258 and 15260 if (specimenEventParameters instanceof TransferEventParameters) { isValidEvent = this.validateSingleTransferEvent(specimenEventParameters, dao, operation,pos1,pos2); } else { isValidEvent = this.validateSingleEvent(specimenEventParameters, dao, operation); } if(!isValidEvent) { return false; } } } else { return this.validateSingleEvent(obj, dao, operation); } return true; } /** * validates transfer event * @param obj - obj * @param dao - dao * @param operation - operation * @param numberOfEvent - numberOfEvent * @param pos1 - pos1 * @param pos2 - pos2 * @return boolean * @throws BizLogicException - BizLogicException */ //Bug 15392 private boolean validateSingleTransferEvent(Object obj, DAO dao, String operation,Integer pos1,Integer pos2) throws BizLogicException { final SpecimenEventParameters eventParameter = (SpecimenEventParameters) obj; final TransferEventParameters parameter = (TransferEventParameters) eventParameter; Specimen specimen; try { specimen = (Specimen)this.retrieveSpecimenLabelName(dao, eventParameter); //this.getSpecimenObject(dao, parameter); Long fromContainerId = null; Integer fromPos1 = null; Integer fromPos2 = null; if (specimen.getSpecimenPosition() != null) { fromContainerId = specimen.getSpecimenPosition().getStorageContainer().getId(); fromPos1 = specimen.getSpecimenPosition().getPositionDimensionOne(); fromPos2 = specimen.getSpecimenPosition().getPositionDimensionTwo(); if(parameter.getFromStorageContainer() == null) { StorageContainer cont = new StorageContainer(); cont.setId(fromContainerId); parameter.setFromStorageContainer(cont); } if(parameter.getFromPositionDimensionOne() == null) { parameter.setFromPositionDimensionOne(fromPos1); } if(parameter.getFromPositionDimensionTwo() == null) { parameter.setFromPositionDimensionTwo(fromPos2); } } if ((fromContainerId == null && parameter.getFromStorageContainer() != null) || (fromContainerId != null && parameter.getFromStorageContainer() == null)) { throw this.getBizLogicException(null, "spec.moved.diff.loc", specimen .getLabel()); } else if ((fromContainerId != null && parameter.getFromStorageContainer() != null) && !((fromContainerId.equals(parameter.getFromStorageContainer().getId()) && fromPos1.equals(parameter.getFromPositionDimensionOne()) && fromPos2 .equals(parameter.getFromPositionDimensionTwo())))) { throw this.getBizLogicException(null, "spec.moved.diff.loc", specimen .getLabel()); } if (parameter.getToStorageContainer() != null && parameter.getToStorageContainer().getName() != null) { final StorageContainer storageContainerObj = parameter.getToStorageContainer(); final List list = this.retrieveStorageContainers(dao, parameter); if (!list.isEmpty()) { storageContainerObj.setId((Long) list.get(0)); parameter.setToStorageContainer(storageContainerObj); } else { //bug 15083 final String message = ApplicationProperties .getValue("transfereventparameters.storageContainer.name"); throw this.getBizLogicException(null, "errors.invalid", message+": " + specimen.getLabel()); } Integer xPos = parameter.getToPositionDimensionOne(); Integer yPos = parameter.getToPositionDimensionTwo(); /** * Following code is added to set the x and y dimension in case only storage container is given * and x and y positions are not given */ if (yPos == null || xPos == null) { String storageValue = null; Position position; try { position = StorageContainerUtil .getFirstAvailablePositionsInContainer(storageContainerObj, this.storageContainerIds, dao,pos1,pos2); storageValue = StorageContainerUtil.getStorageValueKey (storageContainerObj.getName(), null,position.getXPos(), position.getYPos()); storageContainerIds.add(storageValue); } catch (ApplicationException e) { this.LOGGER.error(e.getMessage(), e); throw new BizLogicException(e.getErrorKey(),e,e.getMsgValues()); } if (position != null) { parameter.setToPositionDimensionOne(position.getXPos()); parameter.setToPositionDimensionTwo(position.getYPos()); } else { throw this.getBizLogicException(null, "storage.specified.full", ""); } xPos = parameter.getToPositionDimensionOne(); yPos = parameter.getToPositionDimensionTwo(); } if (xPos == null || yPos == null || xPos.intValue() < 0 || yPos.intValue() < 0) { throw this.getBizLogicException(null, "errors.item.format", ApplicationProperties .getValue("transfereventparameters.toposition")); } } /*else if(parameter.getToStorageContainer() == null || ("").equals(parameter.getToStorageContainer())) { throw this.getBizLogicException(null, "errors.item.format",ApplicationProperties .getValue("transfereventparameters.toposition")); }*/ if (Constants.EDIT.equals(operation)) { //validateTransferEventParameters(eventParameter); } } catch (DAOException exp) { LOGGER.error(exp.getMessage(),exp); throw new BizLogicException(exp.getErrorKey(),exp,exp.getMsgValues()); } return true; } /** * @param obj - Object. * @param dao - DAO object * @param operation - String * @param numberOfEvent - int * @return boolean value * @throws BizLogicException throws BizLogicException. */ private boolean validateSingleEvent(Object obj, DAO dao, String operation) throws BizLogicException { final SpecimenEventParameters eventParameter = (SpecimenEventParameters) obj; ApiSearchUtil.setEventParametersDefault(eventParameter); //End:- Change for API Search /** * Name : Vijay_Pande * Reviewer Name: Sachin_Lale * Bug ID: 4041 * Patch ID: 4041_1 * See also: 1-3 * Description: Container field was not shown as mandatory on SpecimenEventsParameter page. * Now container field is made mandatory. Also validation added for the same. */ final Validator validator = new Validator(); /** -- patch ends here --*/ switch (AppUtility.getEventParametersFormId(eventParameter)) { case Constants.CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID : final String storageStatus = ((CheckInCheckOutEventParameter) eventParameter) .getStorageStatus(); if (!Validator.isEnumeratedValue(Constants.STORAGE_STATUS_ARRAY, storageStatus)) { throw this.getBizLogicException(null, "events.storageStatus.errMsg", ""); } break; case Constants.COLLECTION_EVENT_PARAMETERS_FORM_ID : final String procedure = ((CollectionEventParameters) eventParameter) .getCollectionProcedure(); final List procedureList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_COLLECTION_PROCEDURE, null); if (!Validator.isEnumeratedValue(procedureList, procedure)) { throw this.getBizLogicException(null, "events.collectionProcedure.errMsg", ""); } final String container = ((CollectionEventParameters) eventParameter) .getContainer(); final List containerList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_CONTAINER, null); if (!Validator.isEnumeratedOrNullValue(containerList, container)) { throw this.getBizLogicException(null, "events.container.errMsg", ""); } /** * Name : Vijay_Pande * Patch ID: 4041_2 * See also: 1-3 * Description: Validation for container field. */ if (!validator.isValidOption(container)) { final String message = ApplicationProperties .getValue("collectioneventparameters.container"); throw this.getBizLogicException(null, "errors.item.required", message); } /** -- patch ends here --*/ break; case Constants.EMBEDDED_EVENT_PARAMETERS_FORM_ID : final String embeddingMedium = ((EmbeddedEventParameters) eventParameter) .getEmbeddingMedium(); final List embeddingMediumList = CDEManager.getCDEManager() .getPermissibleValueList(Constants.CDE_NAME_EMBEDDING_MEDIUM, null); if (!Validator.isEnumeratedValue(embeddingMediumList, embeddingMedium)) { throw this.getBizLogicException(null, "events.embeddingMedium.errMsg", ""); } break; case Constants.FIXED_EVENT_PARAMETERS_FORM_ID : final String fixationType = ((FixedEventParameters) eventParameter) .getFixationType(); final List fixationTypeList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_FIXATION_TYPE, null); if (!Validator.isEnumeratedValue(fixationTypeList, fixationType)) { throw this.getBizLogicException(null, "events.fixationType.errMsg", ""); } break; case Constants.FROZEN_EVENT_PARAMETERS_FORM_ID : final String method = ((FrozenEventParameters) eventParameter).getMethod(); final List methodList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_METHOD, null); if (!Validator.isEnumeratedValue(methodList, method)) { throw this.getBizLogicException(null, "events.method.errMsg", ""); } break; case Constants.RECEIVED_EVENT_PARAMETERS_FORM_ID : final String quality = ((ReceivedEventParameters) eventParameter) .getReceivedQuality(); final List qualityList = CDEManager.getCDEManager().getPermissibleValueList( Constants.CDE_NAME_RECEIVED_QUALITY, null); if (!Validator.isEnumeratedValue(qualityList, quality)) { throw this.getBizLogicException(null, "events.receivedQuality.errMsg", ""); } break; case Constants.TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID : final String histQuality = ((TissueSpecimenReviewEventParameters) eventParameter) .getHistologicalQuality(); final List histologicalQualityList = CDEManager.getCDEManager() .getPermissibleValueList(Constants.CDE_NAME_HISTOLOGICAL_QUALITY, null); if (!Validator.isEnumeratedOrNullValue(histologicalQualityList, histQuality)) { throw this.getBizLogicException(null, "events.histologicalQuality.errMsg", ""); } break; //Case added for disposal event for bug #15185 case Constants.DISPOSAL_EVENT_PARAMETERS_FORM_ID : validateDisposalEvent(dao, eventParameter); break; //case added for transfer event validation case Constants.TRANSFER_EVENT_PARAMETERS_FORM_ID: Integer pos1= null; Integer pos2=null; TransferEventParameters trEvent = (TransferEventParameters)eventParameter; pos1 = trEvent.getToPositionDimensionOne(); pos2 = trEvent.getToPositionDimensionTwo(); validateSingleTransferEvent(obj, dao, operation,pos1, pos2); } return true; } /** * @param dao * @param eventParameter * @throws BizLogicException */ private void validateDisposalEvent(DAO dao, final SpecimenEventParameters eventParameter) throws BizLogicException { final DisposalEventParameters disposalEventParameters = (DisposalEventParameters) eventParameter; if (!disposalEventParameters.getActivityStatus().equalsIgnoreCase( Constants.ACTIVITY_STATUS_VALUES[2]) && !disposalEventParameters.getActivityStatus().equalsIgnoreCase( Constants.ACTIVITY_STATUS_VALUES[3])) { LOGGER.info("Invalid Activity Status"); throw this.getBizLogicException(null, "errors.item.selected", ApplicationProperties .getValue("disposaleventparameters.activityStatus")); } long specimenid; try { specimenid = SpecimenUtil.retrieveSpecimenIdByLabelName(dao, eventParameter); if (specimenid != 0) { SpecimenUtil.validateSpecimenStatus( specimenid, dao); } else { throw this.getBizLogicException(null, "Invalid specimen label ", ""); } } catch (DAOException e) { LOGGER.info(e.getMessage(), e); throw this.getBizLogicException(e, e.getErrorKeyAsString(), e.getMessage()); } } /** * @param dao - DAO object. * @param parameter - TransferEventParameters object * @return List of StorageContainers objects. * @throws BizLogicException throws BizLogicException */ private List retrieveStorageContainers(DAO dao, TransferEventParameters parameter) throws BizLogicException { try { final String sourceObjectName = StorageContainer.class.getName(); final String[] selectColumnName = {"id"}; final QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName); queryWhereClause.addCondition(new EqualClause("name", parameter.getToStorageContainer() .getName())); // final List list = dao.retrieve(sourceObjectName, selectColumnName, queryWhereClause); return dao.retrieve(sourceObjectName, selectColumnName, queryWhereClause); } catch (final DAOException daoExp) { this.LOGGER.error(daoExp.getMessage(), daoExp); throw this .getBizLogicException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); } } //removed unused methods // /** // * @param dao : DAO object. // * @param parameter - TransferEventParameters object // * @return Specimen obejct // * @throws BizLogicException throws BizLogicException // */ // private Specimen getSpecimenObject(DAO dao, SpecimenEventParameters parameter) // throws BizLogicException // try // final Specimen specimen = (Specimen) dao.retrieveById(Specimen.class.getName(), // parameter.getSpecimen().getId()); // return specimen; // catch (final DAOException daoExp) // this.LOGGER.error(daoExp.getMessage(), daoExp); // throw this // .getBizLogicException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); /** * @param dao - DAO object. * @param speID - String * @param specimenIds - List of specimenIds * @throws BizLogicException throws BizLogicException * @throws DAOException throws DAOException */ private void disableSubSpecimens(DAO dao, String speID, List specimenIds) throws BizLogicException, DAOException { final String sourceObjectName = Specimen.class.getName(); final String[] selectColumnName = {edu.wustl.common.util.global.Constants.SYSTEM_IDENTIFIER}; final QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName); queryWhereClause.addCondition(new EqualClause("parentSpecimen.id", Long.valueOf(speID))) .andOpr().addCondition( new NotEqualClause(Status.ACTIVITY_STATUS.toString(), Status.ACTIVITY_STATUS_DISABLED.toString())); List listOfSpecimenIDs = dao.retrieve(sourceObjectName, selectColumnName, queryWhereClause); listOfSpecimenIDs = CommonUtilities.removeNull(listOfSpecimenIDs); //getRelatedObjects(dao, Specimen.class, "parentSpecimen", speIDArr); if (!listOfSpecimenIDs.isEmpty()) { if (specimenIds.containsAll(listOfSpecimenIDs)) { return; } final ErrorKey errorKey = ErrorKey.getErrorKey("errors.specimen.contains.subspecimen"); throw new BizLogicException(errorKey, null, ""); } else { return; } } @Override public List getRelatedObjects(DAO dao, Class sourceClass, String[] whereColumnName, String[] whereColumnValue, String[] whereColumnCondition) throws BizLogicException { List list = null; try { final String sourceObjectName = sourceClass.getName(); final String joinCondition = Constants.AND_JOIN_CONDITION; final String selectColumnName[] = {edu.wustl.common.util.global.Constants.SYSTEM_IDENTIFIER}; final QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName); queryWhereClause.getWhereCondition(whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); list = dao.retrieve(sourceObjectName, selectColumnName, queryWhereClause); list = CommonUtilities.removeNull(list); } catch (final DAOException e) { this.LOGGER.error(e.getMessage(), e); throw this.getBizLogicException(e, e.getErrorKeyName(), e.getMsgValues()); } return list; } /** * @return Map of disabled specimen from cache. * @throws Exception throws Exception */ public Map getContForDisabledSpecimenFromCache() throws Exception { // TODO if map is null // TODO move all code to common utility // getting instance of catissueCoreCacheManager and getting participantMap from cache final CatissueCoreCacheManager catissueCoreCacheManager = CatissueCoreCacheManager .getInstance(); final Map disabledconts = (TreeMap) catissueCoreCacheManager .getObjectFromCache(Constants.MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN); return disabledconts; } /** * @param specimenIds - List of specimen ids. * @param sessionDataBean - SessionDataBean object * @param queryString String * @return List of specimen data * @throws BizLogicException throws BizLogicException */ public List getSpecimenDataForBulkOperations(List specimenIds, SessionDataBean sessionDataBean, String queryString) throws BizLogicException { List specimenDataList = null; final JDBCDAO jdbcDao = this.openJDBCSession(); try { final StringBuffer specimenIdsString = new StringBuffer(); specimenIdsString.append('('); for (int i = 0; i < specimenIds.size(); i++) { if (i == (specimenIds.size() - 1)) { specimenIdsString.append(specimenIds.get(i)); } else { specimenIdsString.append(specimenIds.get(i) + ", "); } } specimenIdsString.append(')'); final String sql = queryString + specimenIdsString; specimenDataList = jdbcDao.executeQuery(sql); } catch (final DAOException daoExp) { this.LOGGER.error(daoExp.getMessage(), daoExp); throw this .getBizLogicException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); } finally { this.closeJDBCSession(jdbcDao); } return specimenDataList; } /** * @param operation - String. * @param specimenIds - List of specimen ids. * @param sessionDataBean - SessionDataBean object * @return List of specimen data. * @throws BizLogicException throws BizLogicException */ public List getSpecimenDataForBulkOperations(String operation, List specimenIds, SessionDataBean sessionDataBean) throws BizLogicException { if (operation.equals(Constants.BULK_TRANSFERS)) { return this.getSpecimenDataForBulkTransfers(specimenIds, sessionDataBean); } else { return this.getSpecimenDataForBulkDisposals(specimenIds, sessionDataBean); } } /** * @param specimenIds - List of specim ids. * @param sessionDataBean - SessionDataBean object * @return List of specimen data * @throws BizLogicException throws BizLogicException */ public List getSpecimenDataForBulkTransfers(List specimenIds, SessionDataBean sessionDataBean) throws BizLogicException { final String sql = "Select specimen.IDENTIFIER, specimen.LABEL,abstractSpecimen.SPECIMEN_CLASS, Container.NAME ," + " abstractposition.POSITION_DIMENSION_ONE, abstractposition.POSITION_DIMENSION_TWO, Container.IDENTIFIER," + " abstractSpecimen.SPECIMEN_TYPE,specimen.AVAILABLE_QUANTITY " + " from catissue_specimen specimen left join catissue_abstract_specimen abstractSpecimen on (abstractSpecimen.identifier=specimen.identifier ) " + " left join catissue_specimen_position specimenPosition on (specimen.identifier = specimenPosition.specimen_id) " + " left join catissue_container Container on (specimenPosition.Container_id=Container.IDENTIFIER) " + " left join catissue_abstract_position abstractposition on (abstractposition.Identifier=specimenPosition.IDENTIFIER )" + " where specimen.IDENTIFIER in "; return this.getSpecimenDataForBulkOperations(specimenIds, sessionDataBean, sql); } /** * @param specimenIds - List of specimen ids. * @param sessionDataBean - SessionDataBean object * @return List of specimen data * @throws BizLogicException throws BizLogicException */ public List getSpecimenDataForBulkDisposals(List specimenIds, SessionDataBean sessionDataBean) throws BizLogicException { final String sql = "Select specimen.IDENTIFIER, specimen.LABEL " + "from catissue_specimen specimen " + "where specimen.IDENTIFIER in "; return this.getSpecimenDataForBulkOperations(specimenIds, sessionDataBean, sql); } /** * Called from DefaultBizLogic to get ObjectId for authorization check * (non-Javadoc) * @see edu.wustl.common.bizlogic.DefaultBizLogic#getObjectId(edu.wustl.common.dao.DAO, java.lang.Object) */ @Override public String getObjectId(DAO dao, Object domainObject) throws BizLogicException { String objectId = ""; Long cpId = null; try { if (domainObject instanceof SpecimenEventParameters) { final SpecimenEventParameters specimenEventParameters = (SpecimenEventParameters) domainObject; final AbstractSpecimen specimen = specimenEventParameters.getSpecimen(); // bug 13455 start if (cpId == null) { final IFactory factory = AbstractFactoryConfig.getInstance() .getBizLogicFactory(); final NewSpecimenBizLogic newSpecimenBizLogic = (NewSpecimenBizLogic) factory .getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); cpId = newSpecimenBizLogic.getCPId(dao, cpId, specimen); } objectId = Constants.COLLECTION_PROTOCOL_CLASS_NAME + "_" + cpId; } } catch (final DAOException e) { this.LOGGER.error(e.getMessage(), e); throw new BizLogicException(e); } return objectId; } @Override protected String getPrivilegeKey(Object domainObject) { return Constants.ADD_EDIT_SPECIMEN_EVENTS; } /** * (non-Javadoc) * @throws UserNotAuthorizedException * @throws BizLogicException * @see edu.wustl.common.bizlogic.DefaultBizLogic#isAuthorized(edu.wustl.common.dao.DAO, java.lang.Object, edu.wustl.common.beans.SessionDataBean) * */ @Override public boolean isAuthorized(DAO dao, Object domainObject, SessionDataBean sessionDataBean) throws BizLogicException { boolean isAuthorized = false; boolean validOperation; String protectionElementName = null; String privilegeName = null; try { if (sessionDataBean != null && sessionDataBean.isAdmin()) { return true; } // Get the base object id against which authorization will take place if (domainObject instanceof List) { final List list = (List) domainObject; for (final Object domainObject2 : list) { isAuthorized = checkPrivilegeOnCp(dao,domainObject2,sessionDataBean); } } else { isAuthorized = checkPrivilegeOnCp(dao,domainObject,sessionDataBean); } } catch (final ApplicationException daoExp) { this.LOGGER.error(daoExp.getMessage(), daoExp); throw this .getBizLogicException(daoExp, daoExp.getErrorKeyName(), daoExp.getMsgValues()); } return isAuthorized; } //Extracted Common code from isAuthorized method private boolean checkPrivilegeOnCp(DAO dao,Object domainObject,SessionDataBean sessionDataBean) throws ApplicationException{ if (domainObject instanceof TransferEventParameters) { this.checkPrivilegeOnDestinationSite(dao, domainObject, sessionDataBean); } this.checkPrivilegeOnSourceSite(dao, domainObject, sessionDataBean); String privilegeName = this.getPrivilegeName(domainObject); String protectionElementName = this.getObjectId(dao, domainObject); boolean isAuthorized = AppUtility.checkPrivilegeOnCP(domainObject, protectionElementName, privilegeName, sessionDataBean); if (!isAuthorized) { throw AppUtility.getUserNotAuthorizedException(privilegeName, protectionElementName, domainObject.getClass().getSimpleName()); //bug 11611 and 11659 } return isAuthorized; } /** * @param dao : DAO object. * @param domainObject - Object * @param sessionDataBean -SessionDataBean object * @throws BizLogicException throws BizLogicException */ private void checkPrivilegeOnDestinationSite(DAO dao, Object domainObject, SessionDataBean sessionDataBean) throws BizLogicException { try { final TransferEventParameters tep = (TransferEventParameters) domainObject; StorageContainer container = null; if(tep.getToStorageContainer()==null) { throw this.getBizLogicException(new Exception("User doesn't have privileges to bulk transfer the specimens to virtual position."), null, null); } if (tep.getToStorageContainer().getName() == null && tep.getToStorageContainer().getId() == null) { return; // Case when To & FROM Storage containers are the same } List list = null; if (tep.getToStorageContainer().getId() == null) { list = dao.retrieve(StorageContainer.class.getName(), Constants.NAME, tep .getToStorageContainer().getName()); } else { list = dao.retrieve(StorageContainer.class.getName(), Constants.ID, tep .getToStorageContainer().getId()); } if (list.isEmpty()) { throw this.getBizLogicException(null, "sc.unableToFindContainer", ""); } container = (StorageContainer) list.get(0); final Site site = container.getSite(); final Set<Long> siteIdSet = new UserBizLogic().getRelatedSiteIds(sessionDataBean .getUserId()); if (!siteIdSet.contains(site.getId())) { throw AppUtility.getUserNotAuthorizedException(Constants.Association, site .getObjectId(), domainObject.getClass().getSimpleName()); } } catch (final ApplicationException appExp) { this.LOGGER.error(appExp.getMessage(), appExp); throw this .getBizLogicException(appExp, appExp.getErrorKeyName(), appExp.getMsgValues()); } } /** * @param dao - DAO object. * @param domainObject - Object * @param sessionDataBean - BizLogicException obejct * @throws BizLogicException throws BizLogicException */ private void checkPrivilegeOnSourceSite(DAO dao, Object domainObject, SessionDataBean sessionDataBean) throws BizLogicException { final SpecimenEventParameters spe = (SpecimenEventParameters) domainObject; final AbstractSpecimen specimen = spe.getSpecimen(); List<Long> list = null; Long siteId = null; //SpecimenPosition specimenPosition = null; try { /* specimen = (Specimen) dao.retrieveById(Specimen.class.getName(), specimen.getId()); final Specimen specimen1 = (Specimen) specimen; specimenPosition = specimen1.getSpecimenPosition(); if (specimenPosition != null) // Specimen is NOT Virtually Located { final StorageContainer sc = specimenPosition.getStorageContainer(); final Site site = sc.getSite(); final Set<Long> siteIdSet = new UserBizLogic().getRelatedSiteIds(sessionDataBean .getUserId()); if (!siteIdSet.contains(site.getId())) { //bug 11611 and 11659 start throw AppUtility.getUserNotAuthorizedException(Constants.Association, specimen .getObjectId(), domainObject.getClass().getSimpleName()); //bug 11611 and 11659 end } } */ // bug id 13887 List specimenPositionlist = dao.retrieveAttribute(Specimen.class, "id", specimen .getId(), "specimenPosition"); if (!specimenPositionlist.isEmpty()) // Specimen is NOT Virtually Located { // bug id #13455 start final String query = "select specimen.specimenPosition.storageContainer.site.id from edu.wustl.catissuecore.domain.Specimen as specimen where " + "specimen.id = '" + specimen.getId() + "'"; list = dao.executeQuery(query); final Iterator<Long> itr = list.iterator(); while (itr.hasNext()) { siteId = itr.next(); } final Set<Long> siteIdSet = new UserBizLogic().getRelatedSiteIds(sessionDataBean .getUserId()); if (!siteIdSet.contains(siteId)) { throw AppUtility.getUserNotAuthorizedException(Constants.Association, specimen .getObjectId(), domainObject.getClass().getSimpleName()); } } } catch (final DAOException e) { this.LOGGER.error(e.getMessage(), e); throw this.getBizLogicException(e, e.getErrorKeyName(), e.getMsgValues()); } } public String specimenEventTransferFromMobile(SessionDataBean sessionDataBean,String specimenLabel,String containerName,String pos1,String pos2) throws BizLogicException, DAOException{ DAO dao = null; String msg = ""; try{ String sourceObjectName = StorageContainer.class.getName(); final DefaultBizLogic bizLogic = new DefaultBizLogic(); final QueryWhereClause queryWhereClause = new QueryWhereClause(sourceObjectName); String column = "name"; dao = AppUtility.openDAOSession(sessionDataBean); queryWhereClause.addCondition(new EqualClause(column, containerName)); List<StorageContainer> storageContainerList = dao.retrieve(sourceObjectName, column, containerName); List<Specimen> specimenList = dao.retrieve(Specimen.class.getName(), "label", specimenLabel); if(specimenList == null || specimenList.isEmpty()){ throw new BizLogicException(null, null, Constants.INVALID_LABEL_BARCODE); } if(storageContainerList == null || storageContainerList.isEmpty()) { throw new BizLogicException(null, null, Constants.INVALID_CONTAINER_NAME); } Specimen specimen = specimenList.get(0); TransferEventParameters transferEventParameters = new TransferEventParameters(); if(specimen.getSpecimenPosition()!=null){ transferEventParameters.setFromPositionDimensionOne(specimen.getSpecimenPosition().getPositionDimensionOne()); transferEventParameters.setFromPositionDimensionTwo(specimen.getSpecimenPosition().getPositionDimensionTwo()); transferEventParameters.setFromStorageContainer(specimen.getSpecimenPosition().getStorageContainer()); } List labellingList=StorageContainerUtil.getLabellingSchemeByContainerId(String.valueOf(storageContainerList.get(0).getId())); String oneDimensionLabellingScheme=(String) labellingList.get(0);//((ArrayList)labellingList.get(0)).get(0); String twoDimensionLabellingScheme=(String) labellingList.get(1);//((ArrayList)labellingList.get(0)).get(1); Integer pos1Integer; Integer pos2Integer; if( "".equals(pos1) || "".equals(pos2) || pos1 == null || pos2 == null){ StorageContainerForSpecimenBizLogic scfsBiz = new StorageContainerForSpecimenBizLogic(); List<SpecimenPosition> list = scfsBiz.getAvailablePositionFromContainerForSpecimen(storageContainerList.get(0).getName(),"","",1,dao); pos1Integer = list.get(0).getPositionDimensionOne(); pos2Integer = list.get(0).getPositionDimensionTwo(); }else{ pos1Integer = AppUtility.getPositionValueInInteger(oneDimensionLabellingScheme, pos1); pos2Integer = AppUtility.getPositionValueInInteger(twoDimensionLabellingScheme, pos2); } if(pos1Integer <=0 || pos1Integer > storageContainerList.get(0).getCapacity().getOneDimensionCapacity() || pos2Integer<=0 || pos2Integer >storageContainerList.get(0).getCapacity().getTwoDimensionCapacity()){ throw new BizLogicException(null, null, "Invalid Storage Position."); } transferEventParameters.setSpecimen(specimen); transferEventParameters.setToPositionDimensionOne(pos1Integer); transferEventParameters.setToPositionDimensionTwo(pos2Integer); transferEventParameters.setToStorageContainer(storageContainerList.get(0)); User user = new User(); user.setId(sessionDataBean.getUserId()); transferEventParameters.setUser(user); if(isAuthorized(dao,transferEventParameters,sessionDataBean)){ boolean validate = validateSingleTransferEvent(transferEventParameters,dao,"add",pos1Integer,pos2Integer); if(validate){ insert(transferEventParameters, dao, sessionDataBean); dao.commit(); msg = Constants.TRANSFERED_SUCCESSFUL; } }else{ throw new BizLogicException(null, null, Constants.NO_PERMISSION_TRANSFER_SPECIMEN); } }catch (final ApplicationException exp){ String msgString = ""; if(exp.getErrorKey()!=null ){ msgString= exp.getErrorKey().getMessageWithValues(); }else{ msgString = exp.getMsgValues(); } throw new BizLogicException(exp.getErrorKey(), exp, msgString); } finally { if(dao!=null){ dao.closeSession(); } } return msg; } }
package org.sakaiproject.evaluation.model.constant; /** * Stores constants for use through the Evaluation services, logic layer, and dao layer * Render constants should not be stored here * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class EvalConstants { public final static String TEMPLATE_TYPE_STANDARD = "standard"; /** * Template type: this is an added items template and only used for storing * items added to an evaluation, it cannot be used to start an evaluation */ public final static String TEMPLATE_TYPE_ADDED = "added"; /** * Hierarchy level: this is a special case level which indicates that * these things are at the top level of the hierarchy (nothing is above), * use the constant as the node id {@link #HIERARCHY_NODE_ID_TOP} */ public final static String HIERARCHY_LEVEL_TOP = "toplevel"; /** * Hierarchy node: this is a special case id which represents the top * level of the hierarchy */ public final static String HIERARCHY_NODE_ID_TOP = "000topid"; /** * Hierarchy level: this is the non-special case level that all items * not at the special levels for instructor added items should * have, the node id would be an actual hierarchy node id */ public final static String HIERARCHY_LEVEL_NODE = "nodelevel"; /** * Hierarchy level: instructor level instructor added items exist at this special level, * the userId of the instructor should be used as the node id */ public final static String HIERARCHY_LEVEL_INSTRUCTOR = "instructor"; /** * Hierarchy level: group level instructor added items exist at this at this special level, * the groupId of the group should be used as the node id */ public final static String HIERARCHY_LEVEL_GROUP = "group"; public final static String PERM_WRITE_TEMPLATE = "eval.write.template"; public final static String PERM_ASSIGN_EVALUATION = "eval.assign.evaluation"; public final static String PERM_BE_EVALUATED = "eval.be.evaluated"; public final static String PERM_TAKE_EVALUATION = "eval.take.evaluation"; /** * EvalGroup class: Unknown type */ public final static String GROUP_TYPE_UNKNOWN = "Unknown"; /** * EvalGroup class: Invalid group (this group could not be found in the system) */ public final static String GROUP_TYPE_INVALID = "Invalid"; /** * EvalGroup class: Site type (represents a course or project site) */ public final static String GROUP_TYPE_SITE = "Site"; /** * EvalGroup class: Group type (represents a subgroup within a site) */ public final static String GROUP_TYPE_GROUP = "Group"; /** * EvalGroup class: Provided type (represents an eval group from a provider) */ public final static String GROUP_TYPE_PROVIDED = "Provided"; /** * Scale ideal setting: no selection of this scale is the ideal one */ public static final String SCALE_IDEAL_NONE = null; /** * Scale ideal setting: the lowest (first) selection of this scale is the ideal one */ public static final String SCALE_IDEAL_LOW = "low"; /** * Scale ideal setting: the middle selection of this scale is the ideal one */ public static final String SCALE_IDEAL_MID = "mid"; /** * Scale ideal setting: the highest (last) selection of this scale is the ideal one */ public static final String SCALE_IDEAL_HIGH = "high"; /** * Scale ideal setting: the lowest (first) or highest (last) selections of this scale are the ideal ones */ public static final String SCALE_IDEAL_OUTSIDE = "outside"; /** * Item type (itemClassification) setting: * This is a scaled (likert) type item<br/> * <b>Note:</b> Scaled items could be a block type item, * blocks are a special item type which defines * a chunk of items which all use the same scale */ public static final String ITEM_TYPE_SCALED = "Scaled"; /** * Item type (itemClassification) setting: * This is a textual/essay type item */ public static final String ITEM_TYPE_TEXT = "Essay"; /** * Item type (itemClassification) setting: * This is a header type item, it is only used to customize the look of the * template by providing for a place to add instructions or divisions or titles, * does not count as an actual question item */ public static final String ITEM_TYPE_HEADER = "Header"; /** * Item type (itemClassification) setting: * <b>Note:</b> This is a special type for rendering blocks only * and identifies this as a block parent, generally this should * only be set when creating item blocks and should not be used otherwise * (see implementation notes for details on blocks) */ public static final String ITEM_TYPE_BLOCK_PARENT = "BlockParent"; /** * Item type (itemClassification) setting: * <b>Note:</b> This is a special type for identifying block children only, * if you attempt to save an item or templateItem with this type * it will fail, only use this in the presentation layer * (see implementation notes for details on blocks) */ public static final String ITEM_TYPE_BLOCK_CHILD = "BlockChild"; /** * Item category (itemCategory) setting: * This item is in the course category and will be listed like * normal when the evaluation is rendered for the takers */ public static final String ITEM_CATEGORY_COURSE = "Course"; /** * Item category (itemCategory) setting: * This item is in the instructor category and will be repeated * for each user who can be evaluated in the evaluation group when the * evaluation is rendered for the takers */ public static final String ITEM_CATEGORY_INSTRUCTOR = "Instructor"; /** * Item category (itemCategory) setting: * This item is in the environment category and will be repeated * for each environemnt setup for the evaluation group when the * evaluation is rendered for the takers */ public static final String ITEM_CATEGORY_ENVIRONMENT = "Environment"; /** * Item scale display (scaleDisplaySetting) setting: * Compact scale is displayed left to right on a single line with labels on each end */ public static final String ITEM_SCALE_DISPLAY_COMPACT = "Compact"; /** * Item scale display (scaleDisplaySetting) setting: * Compact scale is displayed left to right on a single line with labels on each end, * colors are applied based on the Scale ideal */ public static final String ITEM_SCALE_DISPLAY_COMPACT_COLORED = "CompactColored"; /** * Item scale display (scaleDisplaySetting) setting: * Full scale is displayed left to right on a single line with labels above each point */ public static final String ITEM_SCALE_DISPLAY_FULL = "Full"; /** * Item scale display (scaleDisplaySetting) setting: * Full scale is displayed left to right on a single line with labels above each point, * colors are applied based on the Scale ideal */ public static final String ITEM_SCALE_DISPLAY_FULL_COLORED = "FullColored"; /** * Item scale display (scaleDisplaySetting) setting: * Stepped scale is displayed left to right on a single line with labels in a stepped pattern above the points */ public static final String ITEM_SCALE_DISPLAY_STEPPED = "Stepped"; /** * Item scale display (scaleDisplaySetting) setting: * Stepped scale is displayed left to right on a single line with labels in a stepped pattern above the points, * colors are applied based on the Scale ideal */ public static final String ITEM_SCALE_DISPLAY_STEPPED_COLORED = "SteppedColored"; /** * Item scale display (scaleDisplaySetting) setting: * Vertical scale is displayed top to bottom with the labels to the right of each point, * NO colored option is available with this type of scale */ public static final String ITEM_SCALE_DISPLAY_VERTICAL = "Vertical"; /** * Template/Item shared setting: Template/Item is controlled by the owner<br/> * (This is a special setting and only used for setting the system setting, don't * store this setting in a template or item, it makes no sense)<br/> * When checking for the system setting, this one allows users to choose the sharing * for their template */ public static final String SHARING_OWNER = "owner"; /** * Template/Item shared setting: Template/Item is visible to the owner only (and super admin) */ public static final String SHARING_PRIVATE = "private"; /** * Template/Item shared setting: Template/Item is visible to owner and any eval admins */ public static final String SHARING_VISIBLE = "visible"; /** * Template/Item shared setting: Template/Item is visible to owner and any admins at the same level in the hierarchy */ public static final String SHARING_SHARED = "shared"; /** * Template/Item shared setting: Template/Item is visible to owner and anyone else in the system * (only a super admin can make a template or item public) */ public static final String SHARING_PUBLIC = "public"; /** * Evaluation instructorOpt setting: * Instructors do not use the evaluation assigned from above by default, * they must take an action to opt in for the evaluation */ public static final String INSTRUCTOR_OPT_IN = "optIn"; /** * Evaluation instructorOpt setting: * Instructors do use the evaluation assigned from above by default, * they must take an action to opt out for the evaluation */ public static final String INSTRUCTOR_OPT_OUT = "optOut"; /** * Evaluation instructorOpt setting: * Instructors must use the evaluation assigned from above by default, * they cannot take an action to opt out for the evaluation and must use it */ public static final String INSTRUCTOR_REQUIRED = "Required"; /** * EmailTemplate: defaultType: Identifies the default created template */ public final static String EMAIL_TEMPLATE_DEFAULT_CREATED = "defaultCreated"; /** * EmailTemplate search setting: * This identifies a template as the "evaluation created template", * used when the evaluation is first created to notify evaluatees that * they may add items to the evaluation and inform them as to when the * evaluation starts */ public static final String EMAIL_TEMPLATE_CREATED = "Created"; /** * EmailTemplate message setting: * This is the default template for when the evaluation is created<br/> * Replaceable strings:<br/> * $EvalTitle - the title of this evaluation * $EvalStartDate - the start date of this evaluation * $EvalDueDate - the due date of this evaluation * $EvalResultsDate - the view results date of this evaluation * $EvalGroupTitle - the title to the site/course/group/evalGroup which this evaluation is assigned to for this user * $HelpdeskEmail - the email address for the helpdesk (or the support contact) * $URLtoAddItems - the direct URL for evaluatees to add items to evals assigned from above * $URLtoTakeEval - the direct URL for evaluators to take this evaluation * $URLtoViewResults - the direct URL to view results for this evaluation * $URLtoSystem - the main URL to the system this is running in */ public static final String EMAIL_CREATED_DEFAULT_TEXT = "All information submitted to the Evaluation System is confidential. Instructors cannot identify which submissions belong to which students. Students are required to login to the system for the sole purpose of providing students access to the appropriate evaluations for their associated courses. Instructors can only view general statistics as allowed by the university. Please send privacy concerns to $HelpdeskEmail. \n" + "\n" + "An evaluation ($EvalTitle) has been created for: $EvalGroupTitle.\n" + "\n"; public static final String EMAIL_CREATED_DEFAULT_TEXT_FOOTER = "\n" + "The evaluation will run from $EvalStartDate to $EvalDueDate and the results of the evaluation will be viewable on $EvalResultsDate.\n" + "\n" + "Thank you for your cooperation.\n" + " "Should you encounter any technical difficulty in working with the evaluation, please send an email to $HelpdeskEmail clearly indicating the problem you encountered. For any other concerns please contact your department.\n"; /** * EmailTemplate message setting: * This is the substitute text for when an evaluation is created to which an instructor may add items<br/> * Replaceable strings:<br/> * $URLtoOptIn - the direct URL for evaluators to opt in to use this evaluation * */ public static final String EMAIL_CREATED_ADD_ITEMS_TEXT = "You may add items to this evaluation until $EvalStartDate using the following link:\n" + "$URLtoAddItems \n"; /** * EmailTemplate message setting: * This is the substitute text for when an evaluation is created to which an instructor may opt in<br/> * Replaceable strings:<br/> * $URLtoOptIn - the direct URL for evaluators to opt in to use this evaluation * */ public static final String EMAIL_CREATED_OPT_IN_TEXT = "Its use is optional. To use the evaluation, you must opt in by using the following link:\n $URLtoOptIn \n\n" + "If you do not opt in, the evaluation will not be used."; /** * EmailTemplate message setting: * This is the substitute text for when an evaluation is created to which an instructor may opt out<br/> * Replaceable strings:<br/> * $URLtoOptOut - the direct URL for evaluators to opt in to use this evaluation */ public static final String EMAIL_CREATED_OPT_OUT_TEXT = "Its use is optional. The evaluation will be used unless you opt out by using the following link:\n $URLtoOptOut \n\n"; /** * EmailTemplate: defaultType: Identifies the default available template */ public final static String EMAIL_TEMPLATE_DEFAULT_AVAILABLE = "defaultAvailable"; /** * EmailTemplate search setting: * This identifies a template as the "evaluation available template", * used when the evaluation is available for users to take */ public static final String EMAIL_TEMPLATE_AVAILABLE = "Available"; /** * EmailTemplate message setting: * This is the default template for when the evaluation is available for users to take * * Replaceable strings:<br/> * $EvalTitle - the title of this evaluation * $EvalDueDate - the due date of this evaluation * $EvalResultsDate - the view results date of this evaluation * $EvalGroupTitle - the title to the site/course/group/evalGroup which this evaluation is assigned to for this user * $HelpdeskEmail - the email address for the helpdesk (or the support contact) * $URLtoTakeEval - the direct URL for evaluators to take this evaluation * $URLtoSystem - the main URL to the system this is running in */ public static final String EMAIL_AVAILABLE_DEFAULT_TEXT = "All information submitted to the Evaluation System is confidential. Instructors cannot identify which submissions belong to which students. Students are required to login to the system for the sole purpose of providing students access to the appropriate evaluations for their associated courses. Instructors can only view general statistics as allowed by the university. Please send privacy concerns to $HelpdeskEmail. \n" + "\n" + "An evaluation ($EvalTitle) for: $EvalGroupTitle is ready to be filled out. Please complete this evaluation by $EvalDueDate at the latest.\n" + "\n" + "You may access the evaluation at:\n" + "$URLtoTakeEval \n" + "If the above link is not working then please follow the Alternate Instructions at the bottom of the message. \n" + "Enter the site using your username and password. You may submit the evaluation once only. \n" + "\n" + "Thank you for your participation.\n" + " "Should you encounter any technical difficulty in filling out the evaluation, please send an email to $HelpdeskEmail clearly indicating the problem you encountered. For any other concerns please contact your department.\n" + "\n" + "Alternate Instructions: \n" + "1) Go to $URLtoSystem \n" + "2) Enter your username and password and click on 'Login' button. \n" + "3) Click on 'Evaluation System' in the left navigation menu under My Workspace. \n" + "4) Click on '$EvalTitle' link under '$EvalGroupTitle'. \n"; /** * EmailTemplate: defaultType: Identifies the default available opt-in template */ public final static String EMAIL_TEMPLATE_DEFAULT_AVAILABLE_OPT_IN = "defaultOptIn"; /** * EmailTemplate search setting: * This identifies a template as the "instructor must opt in for availability template", * used when the evaluation is available for users to take */ public static final String EMAIL_TEMPLATE_AVAILABLE_OPT_IN = "OptIn"; /** * EmailTemplate message setting: * This is the default template for when instructor must opt in for the evaluation to be available for users to take * Replaceable strings:<br/> * $EvalTitle - the title of this evaluation * $EvalStartDate - the start date of this evaluation * $EvalDueDate - the due date of this evaluation * $EvalResultsDate - the view results date of this evaluation * $EvalGroupTitle - the title to the site/course/group/evalGroup which this evaluation is assigned to for this user * $HelpdeskEmail - the email address for the helpdesk (or the support contact) * $URLtoOptIn - the direct URL for evaluators to opt in to use this evaluation * $URLtoSystem - the main URL to the system this is running in */ public static final String EMAIL_AVAILABLE_OPT_IN_TEXT = "All information submitted to the Evaluation System is confidential. Instructors cannot identify which submissions belong to which students. Students are required to login to the system for the sole purpose of providing students access to the appropriate evaluations for their associated courses. Instructors can only view general statistics as allowed by the university. Please send privacy concerns to $HelpdeskEmail. \n" + "\n" + "An evaluation ($EvalTitle) for: $EvalGroupTitle is ready to be filled out. However, you have not opted to use this evaluation.\n" + "\n" + "If you now wish to use the evaluation, you may do so by opting in at:\n" + "$URLtoOptIn \n" + "If the above link is not working then please follow the Alternate Instructions at the bottom of the message. \n" + "Enter the site using your username and password. \n" + "\n" + "Thank you for your participation.\n" + " "Should you encounter any technical difficulty in opting in to the evaluation, please send an email to $HelpdeskEmail clearly indicating the problem you encountered. For any other concerns please contact your department.\n" + "\n" + "Alternate Instructions: \n" + "1) Go to $URLtoSystem \n" + "2) Enter your username and password and click on 'Login' button. \n" + "3) Click on 'Evaluation System' in the left navigation menu under My Workspace. \n" + "4) Click on '$EvalTitle' link under '$EvalGroupTitle'. \n"; /** * EmailTemplate: defaultType: Identifies the default reminder template */ public final static String EMAIL_TEMPLATE_DEFAULT_REMINDER = "defaultReminder"; /** * EmailTemplate search setting: * This identifies a template as the "evaluation reminder template", * used when the evaluation reminder is sent to non-respondent users */ public static final String EMAIL_TEMPLATE_REMINDER = "Reminder"; /** * EmailTemplate message setting: * This is the default template for when the evaluation reminder is sent out */ public static final String EMAIL_REMINDER_DEFAULT_TEXT = "All information submitted to the Evaluation System is confidential. Instructors cannot identify which submissions belong to which students. Students are required to login to the system for the sole purpose of providing students access to the appropriate evaluations for their associated courses. Instructors can only view general statistics as allowed by the university. Please send privacy concerns to $HelpdeskEmail. \n" + "\n" + "We are still awaiting the completion of an evaluation ($EvalTitle) for: $EvalGroupTitle. \n" + "\n" + "You may access the evaluation at: \n" + "$URLtoTakeEval \n" + "If the above link is not working then please follow the Alternate Instructions at the bottom of the message. \n" + "Enter the site using your username and password. Please submit your evaluation by $EvalDueDate. \n" + "\n" + "Thank you for your participation.\n" + " "Should you encounter any technical difficulty in filling out the evaluation, please send an email to $HelpdeskEmail clearly indicating the problem you encountered. For any other concerns please contact your department.\n" + "\n" + "Alternate Instructions: \n" + "1) Go to $URLtoSystem \n" + "2) Enter your username and password and click on 'Login' button. \n" + "3) Click on 'Evaluation System' in the left navigation menu under My Workspace. \n" + "4) Click on '$EvalTitle' link under '$EvalGroupTitle'. \n"; public static final String EMAIL_TEMPLATE_RESULTS = "Results"; public static final String EMAIL_TEMPLATE_DEFAULT_RESULTS = "defaultResults"; public static final String EMAIL_RESULTS_DEFAULT_TEXT = "All information submitted to the Evaluation System is confidential. Instructors cannot identify which submissions belong to which students. Students are required to login to the system for the sole purpose of providing students access to the appropriate evaluations for their associated courses. Instructors can only view general statistics as allowed by the university. Please send privacy concerns to $HelpdeskEmail. \n" + "\n" + "The results of an evaluation ($EvalTitle) for: $EvalGroupTitle are available now.\n" + "\n" + "You may access the evaluation results at: \n" + "$URLtoViewResults \n" + "If the above link is not working then please follow the Alternate Instructions at the bottom of the message. \n" + "Enter the site using your username and password. \n" + "\n" + "Thank you for your participation.\n" + " "Should you encounter any technical difficulty in viewing the evaluation results, please send an email to $HelpdeskEmail clearly indicating the problem you encountered. For any other concerns please contact your department.\n" + "\n" + "Alternate Instructions: \n" + "1) Go to $URLtoSystem \n" + "2) Enter your username and password and click on 'Login' button. \n" + "3) Click on 'Evaluation System' in the left navigation menu under My Workspace. \n" + "4) Click on '$EvalTitle' link under '$EvalGroupTitle'. \n"; /** * Notification: Include all users who have not taken the evaluation yet */ public final static String EMAIL_INCLUDE_NONTAKERS = "nontakers"; /** * Notification: Include all users who have responded to the evaluation */ public final static String EMAIL_INCLUDE_RESPONDENTS = "respondents"; /** * Notification: Include all users for the evaluation */ public final static String EMAIL_INCLUDE_ALL = "all"; /** * Evaluation state: Cannot determine the state, this evaluation is invalid in some way */ public static final String EVALUATION_STATE_UNKNOWN = "UNKNOWN"; /** * Evaluation state: evaluation has not started yet, should be the state of evaluations * when they are first created, can make any change to the evaluation while in this state * <br/>States: InQueue -> Active -> Due -> Closed -> Viewable */ public static final String EVALUATION_STATE_INQUEUE = "InQueue"; /** * Evaluation state: evaluation is currently running, users can take the evaluation, * start date cannot be modified anymore, email templates cannot be modified, * cannot unlink groups of takers at this point, can still add in groups * <br/>States: InQueue -> Active -> Due -> Closed -> Viewable */ public static final String EVALUATION_STATE_ACTIVE = "Active"; /** * Evaluation state: evaluation is over but not technically, no more notifications * will be displayed and links are no longer shown, however, takers * can still complete the evaluation until the state changes to closed, * evaluations in Due status are shown as closed in the interface * <br/>States: InQueue -> Active -> Due -> Closed -> Viewable */ public static final String EVALUATION_STATE_DUE = "Due"; /** * Evaluation state: evaluation is over and closed, * users cannot take evaluation anymore, no changes can be made to the evaluation * except to adjust the results view date, cannot add or remove groups of takers * <br/>States: InQueue -> Active -> Due -> Closed -> Viewable */ public static final String EVALUATION_STATE_CLOSED = "Closed"; /** * Evaluation state: evaluation is over and closed and results are generally viewable, * no changes can be made to the evaluation at all * <br/>States: InQueue -> Active -> Due -> Closed -> Viewable */ public static final String EVALUATION_STATE_VIEWABLE = "Viewable"; /** * Evaluation authentication control: Authentication required to access this evaluation */ public static final String EVALUATION_AUTHCONTROL_AUTH_REQ = "AUTH"; /** * Evaluation authentication control: Authentication key required to access this evaluation (no central auth needed) */ public static final String EVALUATION_AUTHCONTROL_KEY = "KEY"; /** * Evaluation authentication control: Authentication not required to access this evaluation (anonymous allowed) */ public static final String EVALUATION_AUTHCONTROL_NONE = "NONE"; public static final String HIERARCHY_PERM_VIEW_DATA = "HierarchyViewData"; public static final String HIERARCHY_PERM_ASSIGN_EVALUATION = "HierarchyAssignEval"; public static final String HIERARCHY_PERM_CONTROL_TEMPLATES = "HierarchyControlTemplates"; /** * ItemGroup Type: Category (root group type)<br/> * Can contain Objective type groups or Items, must have no parent groups<br/> * Category => Objective => Item */ public static final String ITEM_GROUP_TYPE_CATEGORY = "ItemGroupCategory"; /** * ItemGroup Type: Objective (subgroup of Category)<br/> * Can contain Items, must have at least one category parent group<br/> * Category => Objective => Item */ public static final String ITEM_GROUP_TYPE_OBJECTIVE = "ItemGroupObjective"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * */ public static final String JOB_TYPE_CREATED = "scheduledCreated"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * */ public static final String JOB_TYPE_ACTIVE = "scheduledActive"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * */ public static final String JOB_TYPE_DUE = "scheduledDue"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * */ public static final String JOB_TYPE_CLOSED = "scheduledClosed"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * When separate student and instructor view date is not set * */ public static final String JOB_TYPE_VIEWABLE = "scheduledViewable"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * When separate instructor view date is set * */ public static final String JOB_TYPE_VIEWABLE_INSTRUCTORS = "scheduledViewableInstructors"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * When separate student view date is set * */ public static final String JOB_TYPE_VIEWABLE_STUDENTS = "scheduledViewableStudents"; /** * ScheduledInvocationManager: ScheduledInvocationCommand jobType * */ public static final String JOB_TYPE_REMINDER = "scheduledReminder"; }
package org.openmrs.module.openhmis.cashier.api.util; import java.math.BigDecimal; import org.apache.commons.logging.Log; import org.openmrs.GlobalProperty; import org.openmrs.api.APIException; import org.openmrs.api.AdministrationService; import org.openmrs.api.context.Context; import org.openmrs.messagesource.MessageSourceService; import org.openmrs.module.openhmis.cashier.api.ICashierOptionsService; import org.openmrs.module.openhmis.cashier.api.IDepartmentService; import org.openmrs.module.openhmis.cashier.api.IItemService; import org.openmrs.module.openhmis.cashier.api.model.Bill; import org.openmrs.module.openhmis.cashier.api.model.BillLineItem; import org.openmrs.module.openhmis.cashier.api.model.CashierOptions; import org.openmrs.module.openhmis.cashier.api.model.Department; import org.openmrs.module.openhmis.cashier.api.model.Item; import org.openmrs.module.openhmis.cashier.api.model.ItemPrice; import org.openmrs.module.openhmis.cashier.web.CashierWebConstants; public class RoundingUtil { public static BigDecimal round(BigDecimal value, BigDecimal nearest, CashierOptions.RoundingMode mode) { if (nearest.equals(new BigDecimal(0))) return value; BigDecimal factor = new BigDecimal(1).divide(nearest); int scale = nearest.scale(); switch (mode) { case FLOOR: return value.multiply(factor) .setScale(value.scale(), BigDecimal.ROUND_FLOOR) .divide(factor) .setScale(scale, BigDecimal.ROUND_FLOOR); case CEILING: return value.multiply(factor) .setScale(value.scale(), BigDecimal.ROUND_CEILING) .divide(factor) .setScale(scale, BigDecimal.ROUND_CEILING); default: return value.multiply(factor) .setScale(value.scale(), BigDecimal.ROUND_HALF_UP) .divide(factor) .setScale(scale, BigDecimal.ROUND_HALF_UP); } } public static void setupRoundingDeptAndItem(Log log) { /* * Automatically add rounding item & department */ AdministrationService adminService = Context.getService(AdministrationService.class); String nearest = adminService.getGlobalProperty(CashierWebConstants.ROUND_TO_NEAREST_PROPERTY); if (nearest != null && !nearest.isEmpty() && nearest != "0") { MessageSourceService msgService = Context.getMessageSourceService(); IDepartmentService deptService = Context.getService(IDepartmentService.class); IItemService itemService = Context.getService(IItemService.class); Integer itemId, deptId; try { deptId = Integer.parseInt(adminService.getGlobalProperty(CashierWebConstants.ROUNDING_DEPT_ID)); } catch (NumberFormatException e) { deptId = null; } try { itemId = Integer.parseInt(adminService.getGlobalProperty(CashierWebConstants.ROUNDING_ITEM_ID)); } catch (NumberFormatException e) { itemId = null; } if (deptId == null && itemId == null) { Department department = new Department(); String name = msgService.getMessage("openhmis.cashier.rounding.itemName"); String description = msgService.getMessage("openhmis.cashier.rounding.itemDescription"); department.setName(name); department.setDescription(description); department.setRetired(true); department.setRetireReason("Used by Cashier Module for rounding adjustments."); deptService.save(department); log.info("Created department for rounding item (ID = " + department.getId() + ")..."); adminService.saveGlobalProperty(new GlobalProperty(CashierWebConstants.ROUNDING_DEPT_ID, department.getId().toString())); Item item = new Item(); item.setName(name); item.setDescription(description); item.setDepartment(department); ItemPrice price = new ItemPrice(new BigDecimal(0), name); item.addPrice(price); item.setDefaultPrice(price); itemService.save(item); log.info("Created item for rounding (ID = " + item.getId() + ")..."); adminService.saveGlobalProperty(new GlobalProperty(CashierWebConstants.ROUNDING_ITEM_ID, item.getId().toString())); } } } /** * Add a rounding line item to a bill if necessary * @param bill * @should add a rounding line item with the appropriate value * @should not modify a bill that needs no rounding */ public static void addRoundingLineItem(Bill bill) { ICashierOptionsService cashOptService = Context.getService(ICashierOptionsService.class); CashierOptions options = cashOptService.getOptions(); if (options.getRoundToNearest().equals(BigDecimal.ZERO)) return; if (options.getRoundingItemUuid() == null) throw new APIException("No rounding item specified in options. This must be set in order to use rounding for bill totals."); // Get rounding item IItemService itemService = Context.getService(IItemService.class); Item roundingItem = itemService.getByUuid(options.getRoundingItemUuid()); // Create rounding line item BigDecimal difference = bill.getTotal().subtract(RoundingUtil.round(bill.getTotal(), options.getRoundToNearest(), options.getRoundingMode())); if (difference.equals(BigDecimal.ZERO)) return; ItemPrice roundingPrice = roundingItem.addPrice("Rounding", difference.abs()); // This is a little weird, but order has to be set, and this is the best I can come up with right now int itemOrder; // Try to set line item order to one greater than the order of the last item in the list try { itemOrder = bill.getLineItems().get(bill.getLineItems().size() - 1).getLineItemOrder() + 1; } catch (NullPointerException e) { itemOrder = 0; } BillLineItem lineItem = bill.addLineItem( roundingItem, roundingPrice, difference.compareTo(BigDecimal.ZERO) > 0 ? -1 : 1 ); lineItem.setLineItemOrder(itemOrder); } }
package com.joshuaavalon.wsdeckeditor.config; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.joshuaavalon.wsdeckeditor.R; import com.joshuaavalon.wsdeckeditor.BuildConfig; import org.json.JSONException; import org.json.JSONObject; import timber.log.Timber; public class PreferenceRepository { private final String KEY_FIRST_TIME; private final String KEY_SWIPE_REMOVE; private final String KEY_HIDE_NORMAL; private final String KEY_SHOW_LIMIT; private final String KEY_AUTO_CLOSE; private final String KEY_ADD_IF_NOT_EXIST; private final String KEY_SORT_ORDER; private final String KEY_DECK_ID; private final String KEY_QUICK_HISTORY; private static final String KEY_APP_VERSION = "AppVersion"; @NonNull private final SharedPreferences sharedPreferences; @NonNull private RequestQueue requestQueue; private final String api; private PreferenceRepository(@NonNull final Context context, @NonNull final SharedPreferences sharedPreferences) { requestQueue = Volley.newRequestQueue(context); this.sharedPreferences = sharedPreferences; KEY_FIRST_TIME = context.getString(R.string.pref_is_first); KEY_SWIPE_REMOVE = context.getString(R.string.pref_swipe_remove); KEY_HIDE_NORMAL = context.getString(R.string.pref_hide_normal); KEY_SHOW_LIMIT = context.getString(R.string.pref_show_limit); KEY_AUTO_CLOSE = context.getString(R.string.pref_auto_close); KEY_ADD_IF_NOT_EXIST = context.getString(R.string.pref_add_if_not_exist); KEY_SORT_ORDER = context.getString(R.string.pref_sort_order); KEY_DECK_ID = context.getString(R.string.pref_deck_id); KEY_QUICK_HISTORY = context.getString(R.string.pref_quick_search_history); api = context.getString(R.string.api_url); } public static PreferenceRepository fromDefault(@NonNull final Context context) { return PreferenceRepository.from(context, PreferenceManager.getDefaultSharedPreferences(context)); } public static PreferenceRepository from(@NonNull final Context context, @NonNull final SharedPreferences sharedPreferences) { return new PreferenceRepository(context, sharedPreferences); } public boolean getFirstTime() { return sharedPreferences.getBoolean(KEY_FIRST_TIME, true); } public void setFirstTime(final boolean bool) { final SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(KEY_FIRST_TIME, bool); editor.apply(); } public boolean getSwipeRemove() { return sharedPreferences.getBoolean(KEY_SWIPE_REMOVE, false); } public boolean getHideNormal() { return sharedPreferences.getBoolean(KEY_HIDE_NORMAL, true); } public int getShowLimit() { return Integer.valueOf(sharedPreferences.getString(KEY_SHOW_LIMIT, "200")); } public boolean getAutoClose() { return sharedPreferences.getBoolean(KEY_AUTO_CLOSE, true); } public boolean getAddIfNotExist() { return sharedPreferences.getBoolean(KEY_ADD_IF_NOT_EXIST, false); } public boolean getEnableQuickSearchHistory() { return sharedPreferences.getBoolean(KEY_QUICK_HISTORY, true); } public CardOrder getSortOrder() { return CardOrder.values()[sharedPreferences.getInt(KEY_SORT_ORDER, 0)]; } public void setSortOrder(@NonNull final CardOrder order) { final SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_SORT_ORDER, order.ordinal()); editor.apply(); } public long getSelectedDeck() { return sharedPreferences.getLong(KEY_DECK_ID, -1); } public void setSelectedDeck(final long id) { final SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(KEY_DECK_ID, id); editor.apply(); } public int getAppVerion() { return sharedPreferences.getInt(KEY_APP_VERSION, 0); } public void setAppVerion(final int version) { final SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_APP_VERSION, version); editor.apply(); } public void networkVersion(@NonNull final Response.Listener<Version> listener, @Nullable final Response.ErrorListener errorListener) { requestQueue.add(new StringRequest(Request.Method.GET, api, new Response.Listener<String>() { @Override public void onResponse(String response) { Version version = null; try { final JSONObject jsonObject = new JSONObject(response); final String tag = jsonObject.getString("tag_name"); Timber.i("GitHub Version: %s", tag); version = new Version(tag); } catch (JSONException | IllegalArgumentException e) { Timber.e(e, "GitHub Version Error"); } listener.onResponse(version); } }, errorListener)); } public void needUpdated(@NonNull final Response.Listener<Boolean> listener, @Nullable final Response.ErrorListener errorListener) { networkVersion(new Response.Listener<Version>() { @Override public void onResponse(Version response) { if (response == null) { listener.onResponse(false); return; } final Version currentVersion = new Version(BuildConfig.VERSION_NAME); listener.onResponse(currentVersion.compareTo(response) < 0); } }, errorListener); } }
package com.bardframework.plugin; import org.apache.commons.io.FileUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.*; import org.apache.maven.project.MavenProject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.jar.JarFile; import static org.twdata.maven.mojoexecutor.MojoExecutor.*; @Mojo(name = "standalone", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.RUNTIME) public class BardStandaloneMojo extends AbstractMojo { @Component private MavenProject mavenProject; @Component private MavenSession mavenSession; @Component private BuildPluginManager pluginManager; @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}") private String outputDirectory; @Override public void execute() throws MojoExecutionException, MojoFailureException { String toFileName = outputDirectory + "/" + mavenProject.getName() + "-" + mavenProject.getVersion(); File toFile = new File(toFileName); File resourceDir = new File("src/main/resources"); File confDir = new File(toFile, "conf"); File confNewDir = new File(toFile, "conf.new"); File configScript = new File(toFile, "bin/config.sh"); File binDir = new File(toFile, "bin"); try { // copy resource files to conf. If conf already exist, copy resources to conf.new if (confDir.exists()) { FileUtils.copyDirectory(resourceDir, confNewDir); } else { FileUtils.copyDirectory(resourceDir, confDir); } // copy server.sh InputStream serverInput = getClass().getClassLoader().getResourceAsStream("server.sh"); File serverScript = new File(binDir, "server.sh"); FileUtils.copyInputStreamToFile(serverInput, serverScript); serverInput.close(); serverScript.setExecutable(true); // copy dependencies to lib executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("2.9") ), goal("copy-dependencies"), configuration( element(name("outputDirectory"), toFileName + "/lib") ), executionEnvironment( mavenProject, mavenSession, pluginManager ) ); // copy jar file File jarFile = new File( "target/" + mavenProject.getName() + "-" + mavenProject.getVersion() + ".jar"); FileUtils.copyFileToDirectory(jarFile, toFile); // write config.sh JarFile j = new JarFile(jarFile); if (!configScript.exists() && !configScript.createNewFile()) { throw new MojoExecutionException("Fail to create bin/config.sh"); } PrintWriter writer = new PrintWriter(configScript); writer.println("#/bin/sh"); writer.println(); writer.println("PROJECT=" + mavenProject.getName()); writer.println("VERSION=" + mavenProject.getVersion()); writer.println( "MAIN_CLASS=" + j.getManifest().getMainAttributes().getValue("Main-Class")); writer.close(); } catch (IOException e) { throw new MojoExecutionException("Fail to copy files", e); } } }
package org.biojava.nbio.core.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; /** * This class decompresses an input stream containing data compressed with * the unix "compress" utility (LZC, a LZW variant). This code is based * heavily on the <var>unlzw.c</var> code in <var>gzip-1.2.4</var> (written * by Peter Jannesen) and the original compress code. * * * This version has been modified from the original 0.3-3 version by the * Unidata Program Center (support@xxxxxxxxxxxxxxxx) to make the constructor * public and to fix a couple of bugs. * Also: * - markSupported() returns false * - add uncompress() static method * * @version 0.3-3 06/05/2001 * @author Ronald Tschalar * @author Unidata Program Center * @author Richard Holland - making LZW_MAGIC package-visible. * * @version 0.3-5 2008/01/19 * @author Fred Hansen (zweibieren@yahoo.com) * Fixed available() and the EOF condition for mainloop. * Also added some comments. * * @version 1.0 2018/01/08 * @author Fred Hansen (zweibieren@yahoo.com) * added uncompress(InputStream,OutputStream) * and called it from main(String[]) * and uncompress(String, FileOutputStream) * normalize indentation * rewrite skip method * amend logging code in uncompress(String, FileOutputStream) */ public class UncompressInputStream extends FilterInputStream { private final static Logger logger = LoggerFactory.getLogger(UncompressInputStream.class); /** * @param is the input stream to decompress * @throws IOException if the header is malformed */ public UncompressInputStream(InputStream is) throws IOException { super(is); parse_header(); } @Override public synchronized int read() throws IOException { byte[] one = new byte[1]; int b = read(one, 0, 1); if (b == 1) return (one[0] & 0xff); else return -1; } // string table stuff private static final int TBL_CLEAR = 0x100; private static final int TBL_FIRST = TBL_CLEAR + 1; private int[] tab_prefix; private byte[] tab_suffix; final private int[] zeros = new int[256]; private byte[] stack; // various state private boolean block_mode; private int n_bits; private int maxbits; private int maxmaxcode; private int maxcode; private int bitmask; private int oldcode; private byte finchar; private int stackp; private int free_ent; /* input buffer The input stream must be considered in chunks Each chunk is of length eight times the current code length. Thus the chunk contains eight codes; NOT on byte boundaries. */ final private byte[] data = new byte[10000]; private int bit_pos = 0, // current bitwise location in bitstream end = 0, // index of next byte to fill in data got = 0; // number of bytes gotten by most recent read() private boolean eof = false; private static final int EXTRA = 64; @Override public synchronized int read(byte[] buf, int off, int len) throws IOException { if (eof) return -1; int start = off; /* Using local copies of various variables speeds things up by as * much as 30% ! */ int[] l_tab_prefix = tab_prefix; byte[] l_tab_suffix = tab_suffix; byte[] l_stack = stack; int l_n_bits = n_bits; int l_maxcode = maxcode; int l_maxmaxcode = maxmaxcode; int l_bitmask = bitmask; int l_oldcode = oldcode; byte l_finchar = finchar; int l_stackp = stackp; int l_free_ent = free_ent; byte[] l_data = data; int l_bit_pos = bit_pos; // empty stack if stuff still left int s_size = l_stack.length - l_stackp; if (s_size > 0) { int num = (s_size >= len) ? len : s_size; System.arraycopy(l_stack, l_stackp, buf, off, num); off += num; len -= num; l_stackp += num; } if (len == 0) { stackp = l_stackp; return off - start; } // loop, filling local buffer until enough data has been decompressed main_loop: do { if (end < EXTRA) fill(); int bit_end = (got > 0) ? (end - end % l_n_bits) << 3 // set to a "chunk" boundary : (end << 3) - (l_n_bits - 1); // no more data, set to last code while (l_bit_pos < bit_end) { // handle 1-byte reads correctly if (len == 0) { n_bits = l_n_bits; maxcode = l_maxcode; maxmaxcode = l_maxmaxcode; bitmask = l_bitmask; oldcode = l_oldcode; finchar = l_finchar; stackp = l_stackp; free_ent = l_free_ent; bit_pos = l_bit_pos; return off - start; } // check for code-width expansion if (l_free_ent > l_maxcode) { int n_bytes = l_n_bits << 3; l_bit_pos = (l_bit_pos - 1) + n_bytes - (l_bit_pos - 1 + n_bytes) % n_bytes; l_n_bits++; l_maxcode = (l_n_bits == maxbits) ? l_maxmaxcode : (1 << l_n_bits) - 1; logger.debug("Code-width expanded to ", l_n_bits); l_bitmask = (1 << l_n_bits) - 1; l_bit_pos = resetbuf(l_bit_pos); continue main_loop; } // read next code int pos = l_bit_pos >> 3; int code = (((l_data[pos] & 0xFF) | ((l_data[pos + 1] & 0xFF) << 8) | ((l_data[pos + 2] & 0xFF) << 16)) >> (l_bit_pos & 0x7)) & l_bitmask; l_bit_pos += l_n_bits; // handle first iteration if (l_oldcode == -1) { if (code >= 256) throw new IOException("corrupt input: " + code + " > 255"); l_finchar = (byte) (l_oldcode = code); buf[off++] = l_finchar; len continue; } // handle CLEAR code if (code == TBL_CLEAR && block_mode) { System.arraycopy(zeros, 0, l_tab_prefix, 0, zeros.length); l_free_ent = TBL_FIRST - 1; int n_bytes = l_n_bits << 3; l_bit_pos = (l_bit_pos - 1) + n_bytes - (l_bit_pos - 1 + n_bytes) % n_bytes; l_n_bits = INIT_BITS; l_maxcode = (1 << l_n_bits) - 1; l_bitmask = l_maxcode; logger.debug("Code tables reset"); l_bit_pos = resetbuf(l_bit_pos); continue main_loop; } // setup int incode = code; l_stackp = l_stack.length; // Handle KwK case if (code >= l_free_ent) { if (code > l_free_ent) throw new IOException("corrupt input: code=" + code + ", free_ent=" + l_free_ent); l_stack[--l_stackp] = l_finchar; code = l_oldcode; } // Generate output characters in reverse order while (code >= 256) { l_stack[--l_stackp] = l_tab_suffix[code]; code = l_tab_prefix[code]; } l_finchar = l_tab_suffix[code]; buf[off++] = l_finchar; len // And put them out in forward order s_size = l_stack.length - l_stackp; int num = (s_size >= len) ? len : s_size; System.arraycopy(l_stack, l_stackp, buf, off, num); off += num; len -= num; l_stackp += num; // generate new entry in table if (l_free_ent < l_maxmaxcode) { l_tab_prefix[l_free_ent] = l_oldcode; l_tab_suffix[l_free_ent] = l_finchar; l_free_ent++; } // Remember previous code l_oldcode = incode; // if output buffer full, then return if (len == 0) { n_bits = l_n_bits; maxcode = l_maxcode; bitmask = l_bitmask; oldcode = l_oldcode; finchar = l_finchar; stackp = l_stackp; free_ent = l_free_ent; bit_pos = l_bit_pos; return off - start; } } l_bit_pos = resetbuf(l_bit_pos); } while // old code: (got>0) fails if code width expands near EOF (got > 0 // usually true || l_bit_pos < (end << 3) - (l_n_bits - 1)); // last few bytes n_bits = l_n_bits; maxcode = l_maxcode; bitmask = l_bitmask; oldcode = l_oldcode; finchar = l_finchar; stackp = l_stackp; free_ent = l_free_ent; bit_pos = l_bit_pos; eof = true; return off - start; } /** * Moves the unread data in the buffer to the beginning and resets * the pointers. */ private int resetbuf(int bit_pos) { int pos = bit_pos >> 3; System.arraycopy(data, pos, data, 0, end - pos); end -= pos; return 0; } private void fill() throws IOException { got = in.read(data, end, data.length - 1 - end); if (got > 0) end += got; } @Override public synchronized long skip(long num) throws IOException { return Math.max(0, read(new byte[(int) num])); } @Override public synchronized int available() throws IOException { if (eof) return 0; // the old code was: return in.available(); // it fails because this.read() can return bytes // even after in.available() is zero // -- zweibieren int avail = in.available(); return (avail == 0) ? 1 : avail; } static final int LZW_MAGIC = 0x1f9d; private static final int MAX_BITS = 16; private static final int INIT_BITS = 9; private static final int HDR_MAXBITS = 0x1f; private static final int HDR_EXTENDED = 0x20; private static final int HDR_FREE = 0x40; private static final int HDR_BLOCK_MODE = 0x80; private void parse_header() throws IOException { // read in and check magic number int t = in.read(); if (t < 0) throw new EOFException("Failed to read magic number"); int magic = (t & 0xff) << 8; t = in.read(); if (t < 0) throw new EOFException("Failed to read magic number"); magic += t & 0xff; if (magic != LZW_MAGIC) throw new IOException("Input not in compress format (read " + "magic number 0x" + Integer.toHexString(magic) + ")"); // read in header byte int header = in.read(); if (header < 0) throw new EOFException("Failed to read header"); block_mode = (header & HDR_BLOCK_MODE) > 0; maxbits = header & HDR_MAXBITS; if (maxbits > MAX_BITS) throw new IOException("Stream compressed with " + maxbits + " bits, but can only handle " + MAX_BITS + " bits"); if ((header & HDR_EXTENDED) > 0) throw new IOException("Header extension bit set"); if ((header & HDR_FREE) > 0) throw new IOException("Header bit 6 set"); logger.debug("block mode: {}", block_mode); logger.debug("max bits: {}", maxbits); // initialize stuff maxmaxcode = 1 << maxbits; n_bits = INIT_BITS; maxcode = (1 << n_bits) - 1; bitmask = maxcode; oldcode = -1; finchar = 0; free_ent = block_mode ? TBL_FIRST : 256; tab_prefix = new int[1 << maxbits]; tab_suffix = new byte[1 << maxbits]; stack = new byte[1 << maxbits]; stackp = stack.length; for (int idx = 255; idx >= 0; idx tab_suffix[idx] = (byte) idx; } /** * This stream does not support mark/reset on the stream. * * @return false */ @Override public boolean markSupported() { return false; } /** * Read a named file and uncompress it. * @param fileInName Name of compressed file. * @param out A destination for the result. It is closed after data is sent. * @return number of bytes sent to the output stream, * @throws IOException for any error */ public static long uncompress(String fileInName, FileOutputStream out) throws IOException { long start = System.currentTimeMillis(); long total; try (InputStream fin = new FileInputStream(fileInName)) { total = uncompress(fin, out); } out.close(); if (debugTiming) { long end = System.currentTimeMillis(); logger.info("Decompressed {} bytes", total); UncompressInputStream.logger.info("Time: {} seconds", (end - start) / 1000); } return total; } /** * Read an input stream and uncompress it to an output stream. * @param in the incoming InputStream. It is NOT closed. * @param out the destination OutputStream. It is NOT closed. * @return number of bytes sent to the output stream * @throws IOException for any error */ public static long uncompress(InputStream in, OutputStream out) throws IOException { UncompressInputStream ucis = new UncompressInputStream(in); long total = 0; byte[] buffer = new byte[100000]; while (true) { int bytesRead = ucis.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); total += bytesRead; } return total; } private static final boolean debugTiming = false; /** * Reads a file, uncompresses it, and sends the result to stdout. * Also writes trivial statistics to stderr. * @param args An array with one String element, the name of the file to read. * @throws IOException for any failure */ public static void main(String[] args) throws Exception { if (args.length != 1) { logger.info("Usage: UncompressInputStream <file>"); System.exit(1); } long beg = System.currentTimeMillis(); long tot; try (InputStream in = new FileInputStream(args[0])) { tot = uncompress(in, System.out); } long end = System.currentTimeMillis(); logger.info("Decompressed {} bytes", tot); logger.info("Time: {} seconds", (end - beg) / 1000); } }
package org.biojava3.protmod.structure; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.biojava.bio.structure.Atom; import org.biojava.bio.structure.Calc; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.ResidueNumber; import org.biojava.bio.structure.StructureException; import org.biojava.bio.structure.io.mmcif.chem.PolymerType; import org.biojava.bio.structure.io.mmcif.chem.ResidueType; import org.biojava.bio.structure.io.mmcif.model.ChemComp; import org.biojava3.protmod.ComponentType; public final class StructureUtil { private StructureUtil() { throw new AssertionError(); } /** * * @param group a {@link Group} in structure. * @param isAminoAcid true if it is an amino acid. * @return the {@link StructureGroup} of the group. */ public static StructureGroup getStructureGroup(Group group, boolean isAminoAcid) { ResidueNumber resNum = group.getResidueNumber(); return new StructureGroup(resNum, group.getPDBName(), isAminoAcid); } /** * * @param atom a {@link Atom} in structure. * @param isParentAminoAcid true if the containing group is an amino acid. * @return the {@link StructureAtom} of the atom. */ public static StructureAtom getStructureAtom(Atom atom, boolean isParentAminoAcid) { StructureGroup strucGroup = getStructureGroup(atom.getGroup(), isParentAminoAcid); return new StructureAtom(strucGroup, atom.getName()); } /** * * @param atom1 the first {@link Atom} in structure. * @param isParentAminoAcid1 true if the first containing group is an amino acid.. * @param atom2 the second {@link Atom} in structure. * @param isParentAminoAcid2 true if the second containing group is an amino acid.. * @return the {@link StructureAtomLinkage} of the two atoms. */ public static StructureAtomLinkage getStructureAtomLinkage(Atom atom1, boolean isParentAminoAcid1, Atom atom2, boolean isParentAminoAcid2) { StructureAtom strucAtom1 = getStructureAtom(atom1, isParentAminoAcid1); StructureAtom strucAtom2 = getStructureAtom(atom2, isParentAminoAcid2); double distance = getAtomDistance(atom1, atom2); return new StructureAtomLinkage(strucAtom1, strucAtom2, distance); } /** * * @param atom1 the first {@link Atom} in structure. * @param atom2 the second {@link Atom} in structure. * @return the distance between the two atoms in Angstrom. */ public static double getAtomDistance(Atom atom1, Atom atom2) { double distance; try { distance = Calc.getDistance(atom1, atom2); } catch (StructureException e) { throw new AssertionError(); } return distance; } /** * Find a linkage between two groups within tolerance of bond length, * from potential atoms. * @param group1 the first {@link Group}. * @param group2 the second {@link Group}. * @param potentialNamesOfAtomOnGroup1 potential names of the atom on the first group. * If null, search all atoms on the first group. * @param potentialNamesOfAtomOnGroup2 potential names of the atom on the second group. * If null, search all atoms on the second group. * @param ignoreNCLinkage true to ignore all N-C linkages * @param bondLengthTolerance bond length error tolerance. * @return an array of two Atoms that form bond between each other * if found; null, otherwise. */ public static Atom[] findNearestAtomLinkage(final Group group1, final Group group2, List<String> potentialNamesOfAtomOnGroup1, List<String> potentialNamesOfAtomOnGroup2, final boolean ignoreNCLinkage, double bondLengthTolerance) { List<Atom[]> linkages = findAtomLinkages(group1, group2, potentialNamesOfAtomOnGroup1, potentialNamesOfAtomOnGroup2, ignoreNCLinkage, bondLengthTolerance); Atom[] ret = null; double minDistance = Double.POSITIVE_INFINITY; for (Atom[] linkage : linkages) { double distance; try { distance = Calc.getDistance(linkage[0], linkage[1]); } catch (StructureException e) { throw new AssertionError(); } if (distance < minDistance) { minDistance = distance; ret = linkage; } } return ret; } /** * Find linkages between two groups within tolerance of bond length, * from potential atoms. * @param group1 the first {@link Group}. * @param group2 the second {@link Group}. * @param ignoreNCLinkage true to ignore all N-C linkages * @param bondLengthTolerance bond length error tolerance. * @return a list, each element of which is an array of two Atoms that form bond * between each other. */ public static List<Atom[]> findAtomLinkages(final Group group1, final Group group2, final boolean ignoreNCLinkage, final double bondLengthTolerance) { return findAtomLinkages(group1, group2, null, null, ignoreNCLinkage, bondLengthTolerance); } /** * Find linkages between two groups within tolerance of bond length, * from potential atoms. * @param group1 the first {@link Group}. * @param group2 the second {@link Group}. * @param potentialNamesOfAtomOnGroup1 potential names of the atom on the first group. * If null, search all atoms on the first group. * @param potentialNamesOfAtomOnGroup2 potential names of the atom on the second group. * If null, search all atoms on the second group. * @param ignoreNCLinkage true to ignore all N-C linkages * @param bondLengthTolerance bond length error tolerance. * @return a list, each element of which is an array of two Atoms that form bond * between each other. */ public static List<Atom[]> findAtomLinkages(final Group group1, final Group group2, List<String> potentialNamesOfAtomOnGroup1, List<String> potentialNamesOfAtomOnGroup2, final boolean ignoreNCLinkage, final double bondLengthTolerance) { if (group1==null || group2==null) { throw new IllegalArgumentException("Null group(s)."); } if (bondLengthTolerance<0) { throw new IllegalArgumentException("bondLengthTolerance cannot be negative."); } List<Atom[]> ret = new ArrayList<Atom[]>(); if (potentialNamesOfAtomOnGroup1 == null) { // if empty name, search for all atoms potentialNamesOfAtomOnGroup1 = getAtomNames(group1); } if (potentialNamesOfAtomOnGroup2 == null) { // if empty name, search for all atoms potentialNamesOfAtomOnGroup2 = getAtomNames(group2); } for (String namesOfAtomOnGroup1 : potentialNamesOfAtomOnGroup1) { for (String namesOfAtomOnGroup2 : potentialNamesOfAtomOnGroup2) { Atom[] atoms = findLinkage(group1, group2, namesOfAtomOnGroup1, namesOfAtomOnGroup2, bondLengthTolerance); if (atoms != null) { if (ignoreNCLinkage && ((atoms[0].getName().equals("N") && atoms[1].getName().equals("C")) || (atoms[0].getName().equals("C") && atoms[1].getName().equals("N"))) ) { continue; } ret.add(atoms); } } } return ret; } /** * Find a linkage between two groups within tolerance of bond length. * @param group1 the first {@link Group}. * @param group2 the second {@link Group}. * @param nameOfAtomOnGroup1 atom name of the first group. * @param nameOfAtomOnGroup2 atom name of the second group. * @param bondLengthTolerance bond length error tolerance. * @return an array of two Atoms that form bond between each other * if found; null, otherwise. */ public static Atom[] findLinkage(final Group group1, final Group group2, String nameOfAtomOnGroup1, String nameOfAtomOnGroup2, double bondLengthTolerance) { Atom[] ret = new Atom[2]; double distance; try { ret[0] = group1.getAtom(nameOfAtomOnGroup1); ret[1] = group2.getAtom(nameOfAtomOnGroup2); distance = Calc.getDistance(ret[0], ret[1]); } catch (StructureException e) { return null; } if (ret[0]==null || ret[1]==null) { return null; } float radiusOfAtom1 = ret[0].getElement().getCovalentRadius(); float radiusOfAtom2 = ret[1].getElement().getCovalentRadius(); if (Math.abs(distance-radiusOfAtom1 -radiusOfAtom2) > bondLengthTolerance) { return null; } return ret; } /** * * @param group a {@link Group}. * @return all atom names of the group. */ public static List<String> getAtomNames(Group group) { List<Atom> atoms = group.getAtoms(); if (atoms == null) { return Collections.emptyList(); } int n = atoms.size(); List<String> ret = new ArrayList<String>(n); for (int i=0; i<n; i++) { ret.add(atoms.get(i).getName()); } return ret; } // TODO: this should be replaced when Andreas fix the getAtomGroups("amino"); /** * Get all amino acids in a chain. * @param chain * @return */ public static List<Group> getAminoAcids(Chain chain) { //List<Group> residues = new ArrayList<Group>(); //return chain.getSeqResGroups(); // for (Group group : chain.getAtomGroups()) { // ChemComp cc = group.getChemComp(); // if (ResidueType.lPeptideLinking.equals(cc.getResidueType()) || // PolymerType.PROTEIN_ONLY.contains(cc.getPolymerType())) { // residues.add(group); List<Group> residues = new ArrayList<Group>(chain.getAtomGroups()); residues.retainAll(chain.getSeqResGroups()); // not work because chain.getAtomGroups() may return different object from chain.getSeqResGroups() // add amino acids that do not alinged with the sequence residues List<Group> otherGroups = new ArrayList<Group>(chain.getAtomGroups()); otherGroups.removeAll(chain.getSeqResGroups()); for (Group g : otherGroups) { if (g.hasAminoAtoms()) { residues.add(g); } } return residues; // return chain.getAtomGroups("amino"); } }
package org.chromium.chrome.browser.autofill; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TextView; import org.chromium.chrome.R; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This is the dialog that will act as the java side controller between the * AutofillDialogGlue object and the UI elements on the page. It contains the * title and the content views and relays messages from the backend to them. */ public class AutofillDialog extends AlertDialog implements OnClickListener, OnItemSelectedListener { private static final int ADD_MENU_ITEM_INDEX = -1; private static final int EDIT_MENU_ITEM_INDEX = -2; private final AutofillDialogContentView mContentView; private final AutofillDialogTitleView mTitleView; private final AutofillDialogDelegate mDelegate; private AutofillDialogField[][] mAutofillSectionFieldData = new AutofillDialogField[AutofillDialogConstants.NUM_SECTIONS][]; private AutofillDialogMenuItem[][] mAutofillSectionMenuData = new AutofillDialogMenuItem[AutofillDialogConstants.NUM_SECTIONS][]; private final AutofillDialogMenuItem[][] mDefaultMenuItems = new AutofillDialogMenuItem[AutofillDialogConstants.NUM_SECTIONS][]; private boolean mWillDismiss = false; /** * An interface to handle the interaction with an AutofillDialog object. */ public interface AutofillDialogDelegate { /** * Informs AutofillDialog controller that a menu item was selected. * @param section Section in which a menu item was selected. Should match one of the values * in {@link AutofillDialogConstants}. * @param index Index of the selected menu item. */ public void itemSelected(int section, int index); /** * Informs AutofillDialog controller that an account was selected. * @param index Index of the selected account. */ public void accountSelected(int index); /** * Informs AutofillDialog controller that the view is starting editing. * @param section Section that is being edited. Should match one of the values in * {@link AutofillDialogConstants}. */ public void editingStart(int section); /** * Informs AutofillDialog controller that the view has completed editing. * @param section Section that was being edited. Should match one of the values in * {@link AutofillDialogConstants}. */ public void editingComplete(int section); /** * Informs AutofillDialog controller that the view has cancelled editing. * @param section Section that was being edited. Should match one of the values in * {@link AutofillDialogConstants}. */ public void editingCancel(int section); /** * Informs AutofillDialog controller that the user clicked on the submit button. */ public void dialogSubmit(); /** * Informs AutofillDialog controller that the user clicked on the cancel button. */ public void dialogCancel(); /** * Returns the label string to be used for the given section. * @param section Section for which the label should be returned. * @return The string that should appear on the label for the given section. */ public String getLabelForSection(int section); /** * Returns the bitmap icon associated with the given field. * @param fieldType The field type to return the icon for. * @param input The current user input on the field. * @return The bitmap resource that should be shown on the field. */ public Bitmap getIconForField(int fieldType, String input); /** * Returns the placeholder string associated with the given field. * @param section The section associated with the field. * @param fieldType The field type to return the icon for. * @return The placeholder string that should be shown on the field. */ public String getPlaceholderForField(int section, int fieldType); } protected AutofillDialog(Context context, AutofillDialogDelegate delegate) { super(context); mDelegate = delegate; mTitleView = new AutofillDialogTitleView(getContext()); mTitleView.setOnItemSelectedListener(this); setCustomTitle(mTitleView); ScrollView scroll = new ScrollView(context); mContentView = (AutofillDialogContentView) getLayoutInflater(). inflate(R.layout.autofill_dialog_content, null); String[] labels = new String[AutofillDialogConstants.NUM_SECTIONS]; for (int i = 0; i < AutofillDialogConstants.NUM_SECTIONS; i++) { labels[i] = mDelegate.getLabelForSection(i); } mContentView.initializeLabelsForEachSection(labels); scroll.addView(mContentView); setView(scroll); Resources resources = context.getResources(); setButton(AlertDialog.BUTTON_NEGATIVE, resources.getString(R.string.autofill_negative_button), this); setButton(AlertDialog.BUTTON_POSITIVE, getContext().getResources().getString(R.string.autofill_positive_button), this); mContentView.setOnItemSelectedListener(this); AutofillDialogMenuItem[] billingItems = { new AutofillDialogMenuItem(ADD_MENU_ITEM_INDEX, resources.getString(R.string.autofill_new_billing)), new AutofillDialogMenuItem(EDIT_MENU_ITEM_INDEX, resources.getString(R.string.autofill_edit_billing)) }; AutofillDialogMenuItem[] shippingItems = { new AutofillDialogMenuItem(ADD_MENU_ITEM_INDEX, resources.getString(R.string.autofill_new_shipping)), new AutofillDialogMenuItem(EDIT_MENU_ITEM_INDEX, resources.getString(R.string.autofill_edit_shipping)) }; mDefaultMenuItems[AutofillDialogConstants.SECTION_CC_BILLING] = billingItems; mDefaultMenuItems[AutofillDialogConstants.SECTION_SHIPPING] = shippingItems; String hint = mDelegate.getPlaceholderForField( AutofillDialogConstants.SECTION_CC, AutofillDialogConstants.CREDIT_CARD_VERIFICATION_CODE); Bitmap icon = mDelegate.getIconForField( AutofillDialogConstants.CREDIT_CARD_VERIFICATION_CODE, ""); mContentView.setCVCInfo(hint, icon); } @Override public void dismiss() { if (mWillDismiss) super.dismiss(); } @Override public void show() { mContentView.createAdaptersForEachSection(); super.show(); } @Override public void onClick(DialogInterface dialog, int which) { if (!mContentView.isInEditingMode()) { mWillDismiss = true; if (which == AlertDialog.BUTTON_POSITIVE) mDelegate.dialogSubmit(); else mDelegate.dialogCancel(); return; } int section = mContentView.getCurrentSection(); assert(section != AutofillDialogUtils.INVALID_SECTION); if (which == AlertDialog.BUTTON_POSITIVE) mDelegate.editingComplete(section); else mDelegate.editingCancel(section); mContentView.changeLayoutTo(AutofillDialogContentView.LAYOUT_STEADY); getButton(BUTTON_POSITIVE).setText(R.string.autofill_positive_button); mWillDismiss = false; } @Override public void onItemSelected(AdapterView<?> spinner, View view, int position, long id) { if (spinner.getId() == R.id.accounts_spinner) { mDelegate.accountSelected(position); return; } int section = AutofillDialogUtils.getSectionForSpinnerID(spinner.getId()); if (!selectionShouldChangeLayout(spinner, section, position)) { mDelegate.itemSelected(section, position); return; } mDelegate.editingStart(section); AutofillDialogMenuItem currentItem = (AutofillDialogMenuItem) spinner.getItemAtPosition(position); if (currentItem.mIndex == ADD_MENU_ITEM_INDEX) clearAutofillSectionFieldValues(section); mContentView.changeLayoutTo(AutofillDialogContentView.getLayoutModeForSection(section)); getButton(BUTTON_POSITIVE).setText(R.string.autofill_positive_button_editing); } @Override public void onNothingSelected(AdapterView<?> spinner) { } /** * @param spinner The dropdown that was selected by the user. * @param section The section that the dropdown corresponds to. * @param position The position for the selected item in the dropdown. * @return Whether the selection should cause a layout state change. */ private boolean selectionShouldChangeLayout(AdapterView<?> spinner, int section, int position) { int numDefaultItems = mDefaultMenuItems[section] != null ? mDefaultMenuItems[section].length : 0; return position >= spinner.getCount() - numDefaultItems; } /** * Update account chooser dropdown with given accounts. * @param accounts The accounts to be used for the dropdown. * @param selectedAccountIndex The index of a currently selected account. */ public void updateAccountChooser(String[] accounts, int selectedAccountIndex) { ArrayList<String> combinedItems = new ArrayList<String>(accounts.length); combinedItems.addAll(Arrays.asList(accounts)); mTitleView.updateAccountsAndSelect(combinedItems, selectedAccountIndex); } /** * Notifies the dialog that the underlying model is changed and all sections will be updated. * Any editing should be invalidated. * The dialog should either go to the FETCHING or to the STEADY mode. * @param fetchingIsActive If true, the data is being fetched and is not yet available. */ public void modelChanged(boolean fetchingIsActive) { if (fetchingIsActive) { mContentView.changeLayoutTo(AutofillDialogContentView.LAYOUT_FETCHING); } else { mContentView.changeLayoutTo(AutofillDialogContentView.LAYOUT_STEADY); } } /** * Update notification area with the provided notifications. * @param notifications Array of notifications to be displayed in the dialog. */ public void updateNotificationArea(AutofillDialogNotification[] notifications) { // Clear all the previous notifications CheckBox checkBox = ((CheckBox) findViewById(R.id.top_notification)); checkBox.setVisibility(View.GONE); ViewGroup notificationsContainer = ((ViewGroup) findViewById(R.id.bottom_notifications)); notificationsContainer.removeAllViews(); // Add new notifications for (AutofillDialogNotification notification: notifications) { if (notification.mHasArrow && notification.mHasCheckbox) { // Assuming that there will always be only one top notification. checkBox.setBackgroundColor(notification.mBackgroundColor); checkBox.setTextColor(notification.mTextColor); checkBox.setText(notification.mText); checkBox.setVisibility(View.VISIBLE); } else { TextView notificationView = new TextView(getContext()); notificationView.setBackgroundColor(notification.mBackgroundColor); notificationView.setTextColor(notification.mTextColor); notificationView.setText(notification.mText); notificationView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getContext().getResources().getDimension( R.dimen.autofill_notification_text_size)); int padding = getContext().getResources(). getDimensionPixelSize(R.dimen.autofill_notification_padding); notificationView.setPadding(padding, padding, padding, padding); notificationsContainer.addView(notificationView); notificationsContainer.setVisibility(View.VISIBLE); } } } /** * Update given section with the data provided. This fills out the related {@link EditText} * fields in the layout corresponding to the section. * @param section The section to update with the given data. * @param visible Whether the section should be visible. * @param dialogInputs The array that contains the data for each field in the section. * @param menuItems The array that contains the dropdown items to be shown for the section. * @param selectedMenuItem The menu item that is currently selected or -1 otherwise. */ public void updateSection(int section, boolean visible, AutofillDialogField[] dialogInputs, AutofillDialogMenuItem[] menuItems, int selectedMenuItem) { EditText currentField; String inputValue; for (int i = 0; i < dialogInputs.length; i++) { currentField = (EditText) findViewById(AutofillDialogUtils.getEditTextIDForField( section, dialogInputs[i].mFieldType)); if (AutofillDialogUtils.containsCreditCardInfo(section) && dialogInputs[i].mFieldType == AutofillDialogConstants.CREDIT_CARD_VERIFICATION_CODE) { currentField.setCompoundDrawables( null, null, mContentView.getCVCDrawable(), null); } if (currentField == null) continue; currentField.setHint(dialogInputs[i].mPlaceholder); inputValue = dialogInputs[i].getValue(); if (TextUtils.isEmpty(inputValue)) currentField.setText(""); else currentField.setText(inputValue); } mAutofillSectionFieldData[section] = dialogInputs; mContentView.setVisibilityForSection(section, visible); List<AutofillDialogMenuItem> combinedItems; if (mDefaultMenuItems[section] == null) { combinedItems = Arrays.asList(menuItems); } else { combinedItems = new ArrayList<AutofillDialogMenuItem>( menuItems.length + mDefaultMenuItems[section].length); combinedItems.addAll(Arrays.asList(menuItems)); combinedItems.addAll(Arrays.asList(mDefaultMenuItems[section])); } mContentView.updateMenuItemsForSection(section, combinedItems); mAutofillSectionMenuData[section] = menuItems; } /** * Clears the field values for the given section. * @param section The section to clear the field values for. */ public void clearAutofillSectionFieldData(int section) { AutofillDialogField[] fieldData = mAutofillSectionFieldData[section]; if (fieldData == null) return; for (int i = 0; i < fieldData.length; i++) fieldData[i].setValue(""); } private void clearAutofillSectionFieldValues(int section) { AutofillDialogField[] fieldData = mAutofillSectionFieldData[section]; if (fieldData == null) return; EditText currentField; for (int i = 0; i < fieldData.length; i++) { currentField = (EditText) findViewById(AutofillDialogUtils.getEditTextIDForField( section, fieldData[i].mFieldType)); if (currentField == null) continue; currentField.setText(""); } } /** * Return the array that holds all the data about the fields in the given section. * @param section The section to return the data for. * @return An array containing the data for each field in the given section. */ public AutofillDialogField[] getSection(int section) { AutofillDialogField[] fieldData = mAutofillSectionFieldData[section]; if (fieldData == null) return null; EditText currentField; String currentValue; for (int i = 0; i < fieldData.length; i++) { currentField = (EditText) findViewById(AutofillDialogUtils.getEditTextIDForField( section, fieldData[i].mFieldType)); currentValue = currentField.getText().toString(); if (TextUtils.isEmpty(currentValue)) continue; fieldData[i].setValue(currentValue); } return fieldData; } /** * @return The currently entered or previously saved CVC value in the dialog. */ public String getCvc() { EditText cvcEdit = (EditText) findViewById(R.id.cvc_challenge); if (cvcEdit != null) return cvcEdit.getText().toString(); return ""; } /** * @return Whether the billing address should be used as shipping address. */ public boolean shouldUseBillingForShipping() { return false; } /** * @return Whether the details entered should be saved to the currently active * Wallet account. */ public boolean shouldSaveDetailsInWallet() { return false; } /** * @return Whether the details entered should be saved locally on the device. */ public boolean shouldSaveDetailsLocally() { return false; } /** * Updates the progress for the final transaction with the given value. * @param value The current progress percentage value. */ public void updateProgressBar(double value) { } }
package com.metamx.druid.initialization; import com.fasterxml.jackson.annotation.JsonProperty; public abstract class CuratorDiscoveryConfig { @JsonProperty private String path = null; public String getPath() { return path; } public boolean useDiscovery() { return path != null; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package entitysuggester.client.servlets; import com.google.common.collect.Iterables; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.util.List; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.myrrix.client.translating.TranslatedRecommendedItem; import org.apache.mahout.cf.taste.common.TasteException; /** * * @author nilesh */ public class EntitySuggesterServlet extends AbstractEntitySuggesterServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String pathInfo = request.getPathInfo(); String[] pathComponents = Iterables.toArray(SLASH.split(pathInfo), String.class); if (pathComponents.length == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } try { List<TranslatedRecommendedItem> recommended = getClientRecommender().recommendAnonymous(getPropFilePath("proplist").toURI(), request.getParameter("type"), getHowMany(request), pathComponents); output(request, response, recommended); } catch (URISyntaxException use) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, use.toString()); } catch (NamingException ne) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, ne.toString()); } catch (TasteException te) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, te.toString()); } } protected final void output(HttpServletRequest request, ServletResponse response, List<TranslatedRecommendedItem> items) throws IOException { PrintWriter writer = response.getWriter(); // Always print JSON writer.write('['); boolean first = true; for (TranslatedRecommendedItem item : items) { if (first) { first = false; } else { writer.write(','); } writer.write("[\""); writer.write(item.getItemID()); writer.write("\","); writer.write(Float.toString(item.getValue())); writer.write(']'); } writer.write(']'); } }
package edu.duke.cabig.c3pr.web; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractWizardFormController; import org.springframework.web.servlet.view.RedirectView; import edu.duke.cabig.c3pr.dao.HealthcareSiteDao; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.domain.HealthcareSite; import edu.duke.cabig.c3pr.domain.Identifier; import edu.duke.cabig.c3pr.domain.Participant; import edu.duke.cabig.c3pr.utils.ConfigurationProperty; import edu.duke.cabig.c3pr.utils.Lov; import edu.duke.cabig.c3pr.utils.web.propertyeditors.CustomDaoEditor; import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.AbstractTabbedFlowFormController; import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.Flow; import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.Tab; /** * @author Ramakrishna * */ public class EditParticipantController extends AbstractTabbedFlowFormController<Participant> { private static Log log = LogFactory.getLog(EditParticipantController.class); private ParticipantDao participantDao; private HealthcareSiteDao healthcareSiteDao; protected ConfigurationProperty configurationProperty; public EditParticipantController() { setCommandClass(Participant.class); Flow<Participant> flow = new Flow<Participant>("Edit Participant"); intializeFlows(flow); } protected void intializeFlows(Flow<Participant> flow) { flow.addTab(new Tab<Participant>("Details", "Details", "participant/participant_edit_details") { public Map<String, Object> referenceData() { Map<String, List<Lov>> configMap = configurationProperty .getMap(); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("administrativeGenderCode", configMap .get("administrativeGenderCode")); refdata .put("ethnicGroupCode", configMap .get("ethnicGroupCode")); refdata.put("raceCode", configMap.get("raceCode")); refdata.put("source", healthcareSiteDao.getAll()); refdata.put("searchTypeRefData", configMap .get("participantSearchType")); refdata.put("identifiersTypeRefData", configMap .get("participantIdentifiersType")); ; return refdata; } }); flow.addTab(new Tab<Participant>("Identifiers", "Identifiers", "participant/participant_edit_identifiers") { public Map<String, Object> referenceData() { Map<String, List<Lov>> configMap = configurationProperty .getMap(); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("administrativeGenderCode", configMap .get("administrativeGenderCode")); refdata .put("ethnicGroupCode", configMap .get("ethnicGroupCode")); refdata.put("raceCode", configMap.get("raceCode")); refdata.put("source", healthcareSiteDao.getAll()); refdata.put("searchTypeRefData", configMap .get("participantSearchType")); refdata.put("identifiersTypeRefData", configMap .get("participantIdentifiersType")); ; return refdata; } }); flow.addTab(new Tab<Participant>("Address", "Address", "participant/participant_edit_addresses") { public Map<String, Object> referenceData() { Map<String, List<Lov>> configMap = configurationProperty .getMap(); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("searchTypeRefData", configMap .get("participantSearchType")); return refdata; } }); flow.addTab(new Tab<Participant>("Contact Info", "Contact Info", "participant/participant_edit_contactInfo") { public Map<String, Object> referenceData() { Map<String, List<Lov>> configMap = configurationProperty .getMap(); Map<String, Object> refdata = new HashMap<String, Object>(); refdata.put("searchTypeRefData", configMap .get("participantSearchType")); return refdata; } }); setFlow(flow); } @Override protected Map<String, Object> referenceData( HttpServletRequest httpServletRequest, int page) throws Exception { // Currently the static data is a hack, once DB design is approved for // an LOV this will be // replaced with LOVDao to get the static data from individual tables Map<String, Object> refdata = new HashMap<String, Object>(); Map<String, List<Lov>> configMap = configurationProperty.getMap(); if (("update") .equals((httpServletRequest.getParameter("_updateaction")))) switch (page) { case 0: refdata.put("updateMessageRefData", configMap.get( "editParticipantMessages").get(0)); break; case 1: refdata.put("updateMessageRefData", configMap.get( "editParticipantMessages").get(1)); break; case 2: refdata.put("updateMessageRefData", configMap.get( "editParticipantMessages").get(2)); break; case 3: refdata.put("updateMessageRefData", configMap.get( "editParticipantMessages").get(3)); break; default: refdata.put("updateMessageRefData", configMap.get( "editParticipantMessages").get(4)); } return refdata; } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest) */ @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { Participant participant = null; if (request.getParameter("participantId") != null) { System.out.println(" Request URl is:" + request.getRequestURL().toString()); participant = participantDao.getById(Integer.parseInt(request .getParameter("participantId")), true); System.out.println(" Participant's ID is:" + participant.getId()); } if (participant.getIdentifiers().size() == 0) { Identifier temp = new Identifier(); temp.setSource("<enter value>"); temp.setType("<enter value>"); temp.setValue("<enter value>"); temp.setPrimaryIndicator(false); participant.addIdentifier(temp); } return participant; } @Override protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) throws Exception { binder.registerCustomEditor(Date.class, new CustomDateEditor( new SimpleDateFormat("MM/dd/yyyy"), true)); binder.registerCustomEditor(HealthcareSite.class, new CustomDaoEditor( healthcareSiteDao)); } @Override protected void postProcessPage(HttpServletRequest request, Object oCommand, Errors errors, int page) throws Exception { Participant participant = (Participant) oCommand; if (page == 1) { handleIdentifierAction(participant, request.getParameter("_action"), request .getParameter("_selected")); } if (("update").equals(request.getParameter("_updateaction"))) { Iterator<Identifier> iterator = participant.getIdentifiers() .iterator(); while (iterator.hasNext()) { Identifier identifier = iterator.next(); if (identifier.getSource().trim().equals("<enter value>") || identifier.getType().trim().equals("<enter value>") || identifier.getValue().equals("<enter value>")) { iterator.remove(); } } try { log.debug("Updating Participant"); participantDao.save(participant); } catch (RuntimeException e) { log.debug("Unable to update Participant"); e.printStackTrace(); } } } @Override protected ModelAndView processFinish(HttpServletRequest request, HttpServletResponse response, Object oCommand, BindException errors) throws Exception { ModelAndView modelAndView = new ModelAndView(new RedirectView( "searchparticipant.do")); return modelAndView; } private void handleIdentifierAction(Participant participant, String action, String selected) { if ("addIdentifier".equals(action)) { log.debug("Requested Add Identifier"); Identifier id = new Identifier(); id.setSource("<enter value>"); id.setType("<enter value>"); id.setValue("<enter value>"); participant.addIdentifier(id); } else if ("removeIdentifier".equals(action)) { log.debug("Requested Remove Identifier"); participant.getIdentifiers().remove(Integer.parseInt(selected)); } } public HealthcareSiteDao getHealthcareSiteDao() { return healthcareSiteDao; } public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) { this.healthcareSiteDao = healthcareSiteDao; } public ParticipantDao getParticipantDao() { return participantDao; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } public ConfigurationProperty getConfigurationProperty() { return configurationProperty; } public void setConfigurationProperty( ConfigurationProperty configurationProperty) { this.configurationProperty = configurationProperty; } }
/** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. * TEMPLATE: SpringServiceImpl.vsl in andromda-spring cartridge * MODEL CLASS: AndroMDAModel::ctsms::org.phoenixctms.ctsms::service::proband::ProbandService * STEREOTYPE: Service */ package org.phoenixctms.ctsms.service.proband; import java.awt.Dimension; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.crypto.SecretKey; import org.hibernate.LockMode; import org.phoenixctms.ctsms.adapt.DiagnosisCollisionFinder; import org.phoenixctms.ctsms.adapt.InquiryValueCollisionFinder; import org.phoenixctms.ctsms.adapt.MaxCostTypesAdapter; import org.phoenixctms.ctsms.adapt.MedicationCollisionFinder; import org.phoenixctms.ctsms.adapt.ProbandAddressTypeTagAdapter; import org.phoenixctms.ctsms.adapt.ProbandContactDetailTypeTagAdapter; import org.phoenixctms.ctsms.adapt.ProbandStatusEntryCollisionFinder; import org.phoenixctms.ctsms.adapt.ProbandTagAdapter; import org.phoenixctms.ctsms.adapt.ProcedureCollisionFinder; import org.phoenixctms.ctsms.compare.InquiryValueOutVOComparator; import org.phoenixctms.ctsms.compare.ProbandStatusEntryIntervalComparator; import org.phoenixctms.ctsms.domain.AlphaId; import org.phoenixctms.ctsms.domain.AnimalContactParticulars; import org.phoenixctms.ctsms.domain.Asp; import org.phoenixctms.ctsms.domain.AspDao; import org.phoenixctms.ctsms.domain.AspSubstance; import org.phoenixctms.ctsms.domain.AspSubstanceDao; import org.phoenixctms.ctsms.domain.BankAccount; import org.phoenixctms.ctsms.domain.BankAccountDao; import org.phoenixctms.ctsms.domain.Department; import org.phoenixctms.ctsms.domain.Diagnosis; import org.phoenixctms.ctsms.domain.DiagnosisDao; import org.phoenixctms.ctsms.domain.File; import org.phoenixctms.ctsms.domain.FileDao; import org.phoenixctms.ctsms.domain.InputField; import org.phoenixctms.ctsms.domain.InputFieldDao; import org.phoenixctms.ctsms.domain.InputFieldValue; import org.phoenixctms.ctsms.domain.Inquiry; import org.phoenixctms.ctsms.domain.InquiryDao; import org.phoenixctms.ctsms.domain.InquiryValue; import org.phoenixctms.ctsms.domain.InquiryValueDao; import org.phoenixctms.ctsms.domain.InventoryBookingDao; import org.phoenixctms.ctsms.domain.JournalEntry; import org.phoenixctms.ctsms.domain.JournalEntryDao; import org.phoenixctms.ctsms.domain.MassMailRecipient; import org.phoenixctms.ctsms.domain.MassMailRecipientDao; import org.phoenixctms.ctsms.domain.Medication; import org.phoenixctms.ctsms.domain.MedicationDao; import org.phoenixctms.ctsms.domain.MimeType; import org.phoenixctms.ctsms.domain.MoneyTransfer; import org.phoenixctms.ctsms.domain.MoneyTransferDao; import org.phoenixctms.ctsms.domain.NotificationDao; import org.phoenixctms.ctsms.domain.OpsCode; import org.phoenixctms.ctsms.domain.PrivacyConsentStatusType; import org.phoenixctms.ctsms.domain.PrivacyConsentStatusTypeDao; import org.phoenixctms.ctsms.domain.Proband; import org.phoenixctms.ctsms.domain.ProbandAddress; import org.phoenixctms.ctsms.domain.ProbandAddressDao; import org.phoenixctms.ctsms.domain.ProbandCategory; import org.phoenixctms.ctsms.domain.ProbandContactDetailValue; import org.phoenixctms.ctsms.domain.ProbandContactDetailValueDao; import org.phoenixctms.ctsms.domain.ProbandContactParticulars; import org.phoenixctms.ctsms.domain.ProbandDao; import org.phoenixctms.ctsms.domain.ProbandGroup; import org.phoenixctms.ctsms.domain.ProbandGroupDao; import org.phoenixctms.ctsms.domain.ProbandListEntry; import org.phoenixctms.ctsms.domain.ProbandStatusEntry; import org.phoenixctms.ctsms.domain.ProbandStatusEntryDao; import org.phoenixctms.ctsms.domain.ProbandStatusType; import org.phoenixctms.ctsms.domain.ProbandTagValue; import org.phoenixctms.ctsms.domain.ProbandTagValueDao; import org.phoenixctms.ctsms.domain.Procedure; import org.phoenixctms.ctsms.domain.ProcedureDao; import org.phoenixctms.ctsms.domain.Staff; import org.phoenixctms.ctsms.domain.Trial; import org.phoenixctms.ctsms.domain.TrialDao; import org.phoenixctms.ctsms.domain.User; import org.phoenixctms.ctsms.domain.VisitScheduleItem; import org.phoenixctms.ctsms.domain.VisitScheduleItemDao; import org.phoenixctms.ctsms.enumeration.FileModule; import org.phoenixctms.ctsms.enumeration.JournalModule; import org.phoenixctms.ctsms.enumeration.PaymentMethod; import org.phoenixctms.ctsms.enumeration.Sex; import org.phoenixctms.ctsms.enumeration.VariablePeriod; import org.phoenixctms.ctsms.excel.VisitScheduleExcelWriter; import org.phoenixctms.ctsms.exception.ServiceException; import org.phoenixctms.ctsms.pdf.PDFImprinter; import org.phoenixctms.ctsms.pdf.ProbandLetterPDFPainter; import org.phoenixctms.ctsms.security.CipherText; import org.phoenixctms.ctsms.security.CryptoUtil; import org.phoenixctms.ctsms.security.reencrypt.ReEncrypter; import org.phoenixctms.ctsms.util.CheckIDUtil; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.util.CoreUtil; import org.phoenixctms.ctsms.util.DefaultSettings; import org.phoenixctms.ctsms.util.L10nUtil; import org.phoenixctms.ctsms.util.L10nUtil.Locales; import org.phoenixctms.ctsms.util.ServiceExceptionCodes; import org.phoenixctms.ctsms.util.ServiceUtil; import org.phoenixctms.ctsms.util.SettingCodes; import org.phoenixctms.ctsms.util.Settings; import org.phoenixctms.ctsms.util.Settings.Bundle; import org.phoenixctms.ctsms.util.SystemMessageCodes; import org.phoenixctms.ctsms.util.date.DateCalc; import org.phoenixctms.ctsms.util.date.DateInterval; import org.phoenixctms.ctsms.vo.AuthenticationVO; import org.phoenixctms.ctsms.vo.BankAccountInVO; import org.phoenixctms.ctsms.vo.BankAccountOutVO; import org.phoenixctms.ctsms.vo.DiagnosisInVO; import org.phoenixctms.ctsms.vo.DiagnosisOutVO; import org.phoenixctms.ctsms.vo.InquiriesPDFVO; import org.phoenixctms.ctsms.vo.InquiryValueInVO; import org.phoenixctms.ctsms.vo.InquiryValueJsonVO; import org.phoenixctms.ctsms.vo.InquiryValueOutVO; import org.phoenixctms.ctsms.vo.InquiryValuesOutVO; import org.phoenixctms.ctsms.vo.InventoryBookingOutVO; import org.phoenixctms.ctsms.vo.MedicationInVO; import org.phoenixctms.ctsms.vo.MedicationOutVO; import org.phoenixctms.ctsms.vo.MoneyTransferInVO; import org.phoenixctms.ctsms.vo.MoneyTransferOutVO; import org.phoenixctms.ctsms.vo.PSFVO; import org.phoenixctms.ctsms.vo.ProbandAddressInVO; import org.phoenixctms.ctsms.vo.ProbandAddressOutVO; import org.phoenixctms.ctsms.vo.ProbandContactDetailValueInVO; import org.phoenixctms.ctsms.vo.ProbandContactDetailValueOutVO; import org.phoenixctms.ctsms.vo.ProbandGroupOutVO; import org.phoenixctms.ctsms.vo.ProbandImageInVO; import org.phoenixctms.ctsms.vo.ProbandImageOutVO; import org.phoenixctms.ctsms.vo.ProbandInVO; import org.phoenixctms.ctsms.vo.ProbandLetterPDFVO; import org.phoenixctms.ctsms.vo.ProbandOutVO; import org.phoenixctms.ctsms.vo.ProbandStatusEntryInVO; import org.phoenixctms.ctsms.vo.ProbandStatusEntryOutVO; import org.phoenixctms.ctsms.vo.ProbandTagValueInVO; import org.phoenixctms.ctsms.vo.ProbandTagValueOutVO; import org.phoenixctms.ctsms.vo.ProcedureInVO; import org.phoenixctms.ctsms.vo.ProcedureOutVO; import org.phoenixctms.ctsms.vo.ReimbursementsExcelVO; import org.phoenixctms.ctsms.vo.TrialOutVO; import org.phoenixctms.ctsms.vo.VisitScheduleExcelVO; import org.phoenixctms.ctsms.vo.VisitScheduleItemOutVO; import org.phoenixctms.ctsms.vocycle.ProbandReflexionGraph; /** * @see org.phoenixctms.ctsms.service.proband.ProbandService */ public class ProbandServiceImpl extends ProbandServiceBase { private static JournalEntry logSystemMessage(Proband proband, ProbandAddressOutVO addressVO, Timestamp now, User modified, String systemMessageCode, Object result, Object original, JournalEntryDao journalEntryDao) throws Exception { boolean journalEncrypted = CommonUtil.getUseJournalEncryption(JournalModule.PROBAND_JOURNAL, null); return journalEntryDao.addSystemMessage(proband, now, modified, systemMessageCode, journalEncrypted ? new Object[] { addressVO.getName() } : null, new Object[] { CoreUtil.getSystemMessageCommentContent(result, original, !journalEncrypted) }); } private static JournalEntry logSystemMessage(Trial trial, ProbandOutVO probandVO, Timestamp now, User modified, String systemMessageCode, Object result, Object original, JournalEntryDao journalEntryDao) throws Exception { boolean journalEncrypted = CommonUtil.getUseJournalEncryption(JournalModule.PROBAND_JOURNAL, null); return journalEntryDao.addSystemMessage(trial, now, modified, systemMessageCode, journalEncrypted ? new Object[] { CommonUtil.probandOutVOToString(probandVO) } : new Object[] { Long.toString(probandVO.getId()) }, new Object[] { CoreUtil.getSystemMessageCommentContent(result, original, !journalEncrypted) }); } private void addUpdateInquiryValue(InquiryValueInVO inquiryValueIn, Proband proband, Inquiry inquiry, Timestamp now, User user, boolean force, boolean logTrial, boolean logProband, ArrayList<InquiryValueOutVO> outInquiryValues, ArrayList<InquiryValueJsonVO> outJsInquiryValues) throws Exception { InquiryValueDao inquiryValueDao = this.getInquiryValueDao(); Long id = inquiryValueIn.getId(); InquiryValueOutVO result = null; InquiryValueJsonVO resultJs = null; JournalEntryDao journalEntryDao = this.getJournalEntryDao(); if (id == null) { if (inquiry.isDisabled()) { inquiryValueIn = ServiceUtil.createPresetInquiryInValue(inquiry, proband.getId(), this.getInputFieldSelectionSetValueDao()); } checkInquiryValueInput(inquiryValueIn, proband, inquiry); ServiceUtil.addAutocompleteSelectionSetValue(inquiry.getField(), inquiryValueIn.getTextValue(), now, user, this.getInputFieldSelectionSetValueDao(), journalEntryDao); InquiryValue inquiryValue = inquiryValueDao.inquiryValueInVOToEntity(inquiryValueIn); CoreUtil.modifyVersion(inquiryValue, now, user); InputFieldValue inputFieldValue = inquiryValue.getValue(); this.getInputFieldValueDao().create(inputFieldValue); inquiryValue = inquiryValueDao.create(inquiryValue); if (outInquiryValues != null || logTrial || logProband) { result = inquiryValueDao.toInquiryValueOutVO(inquiryValue); } if (outJsInquiryValues != null && !CommonUtil.isEmptyString(inquiry.getJsVariableName())) { resultJs = inquiryValueDao.toInquiryValueJsonVO(inquiryValue); } if (logProband) { ServiceUtil.logSystemMessage(proband, result.getInquiry().getTrial(), now, user, SystemMessageCodes.INQUIRY_VALUE_CREATED, result, null, journalEntryDao); } if (logTrial) { ServiceUtil.logSystemMessage(inquiry.getTrial(), result.getProband(), now, user, SystemMessageCodes.INQUIRY_VALUE_CREATED, result, null, journalEntryDao); } } else { InquiryValue originalInquiryValue = CheckIDUtil.checkInquiryValueId(id, inquiryValueDao); if (!inquiry.isDisabled() && !ServiceUtil.inquiryValueEquals(inquiryValueIn, originalInquiryValue.getValue(), force)) { checkInquiryValueInput(inquiryValueIn, proband, inquiry); ServiceUtil.addAutocompleteSelectionSetValue(inquiry.getField(), inquiryValueIn.getTextValue(), now, user, this.getInputFieldSelectionSetValueDao(), journalEntryDao); InquiryValueOutVO original = null; if (logProband || logTrial) { original = inquiryValueDao.toInquiryValueOutVO(originalInquiryValue); } inquiryValueDao.evict(originalInquiryValue); InquiryValue inquiryValue = inquiryValueDao.inquiryValueInVOToEntity(inquiryValueIn); CoreUtil.modifyVersion(originalInquiryValue, inquiryValue, now, user); inquiryValueDao.update(inquiryValue); if (outInquiryValues != null || logTrial || logProband) { result = inquiryValueDao.toInquiryValueOutVO(inquiryValue); } if (outJsInquiryValues != null && !CommonUtil.isEmptyString(inquiry.getJsVariableName())) { resultJs = inquiryValueDao.toInquiryValueJsonVO(inquiryValue); } if (logProband) { ServiceUtil.logSystemMessage(proband, result.getInquiry().getTrial(), now, user, SystemMessageCodes.INQUIRY_VALUE_UPDATED, result, original, journalEntryDao); } if (logTrial) { ServiceUtil .logSystemMessage(inquiry.getTrial(), result.getProband(), now, user, SystemMessageCodes.INQUIRY_VALUE_UPDATED, result, original, journalEntryDao); } } else { if (outInquiryValues != null) { result = inquiryValueDao.toInquiryValueOutVO(originalInquiryValue); } if (outJsInquiryValues != null && !CommonUtil.isEmptyString(inquiry.getJsVariableName())) { resultJs = inquiryValueDao.toInquiryValueJsonVO(originalInquiryValue); } } } if (outInquiryValues != null) { outInquiryValues.add(result); } if (resultJs != null) { outJsInquiryValues.add(resultJs); } } private void checkBankAccountInput(BankAccountInVO bankAccountIn) throws ServiceException { ProbandDao probandDao = this.getProbandDao(); // referential checks Proband proband = CheckIDUtil.checkProbandId(bankAccountIn.getProbandId(), probandDao); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } if (!proband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BANK_ACCOUNT_PROBAND_NOT_PERSON); } ServiceUtil.checkProbandLocked(proband); String iban = bankAccountIn.getIban(); String bic = bankAccountIn.getBic(); String accountNumber = bankAccountIn.getAccountNumber(); String bankCodeNumber = bankAccountIn.getBankCodeNumber(); if (bankAccountIn.getNa()) { if (bankAccountIn.getAccountHolderName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ACCOUNT_HOLDER_NAME_NOT_NULL); } if (bankAccountIn.getBankName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BANK_NAME_NOT_NULL); } if (iban != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.IBAN_NOT_NULL); } if (bic != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BIC_NOT_NULL); } if (accountNumber != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ACCOUNT_NUMBER_NOT_NULL); } if (bankCodeNumber != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BANK_CODE_NUMBER_NOT_NULL); } } else { if (CommonUtil.isEmptyString(bankAccountIn.getAccountHolderName())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ACCOUNT_HOLDER_NAME_REQUIRED); } if (CommonUtil.isEmptyString(iban) != CommonUtil.isEmptyString(bic)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BANK_ACCOUNT_IBAN_AND_BIC_REQUIRED); } if (!CommonUtil.isEmptyString(iban) && !CommonUtil.checkIban(iban)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_IBAN); } if (!CommonUtil.isEmptyString(bic) && !CommonUtil.checkBic(bic)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_BIC); } if (CommonUtil.isEmptyString(accountNumber) != CommonUtil.isEmptyString(bankCodeNumber)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BANK_ACCOUNT_ACCOUNT_NUMBER_AND_BANK_CODE_NUMBER_REQUIRED); } if (CommonUtil.isEmptyString(iban) && CommonUtil.isEmptyString(accountNumber)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.IBAN_OR_BANK_ACCOUNT_ACCOUNT_NUMBER_REQUIRED); } } } private void checkDiagnosisInput(DiagnosisInVO diagnosisIn) throws ServiceException { ProbandDao probandDao = this.getProbandDao(); // referential checks Proband proband = CheckIDUtil.checkProbandId(diagnosisIn.getProbandId(), probandDao); AlphaId alphaId = CheckIDUtil.checkAlphaIdId(diagnosisIn.getCodeId(), this.getAlphaIdDao()); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ServiceUtil.checkProbandLocked(proband); if (diagnosisIn.getStart() == null && diagnosisIn.getStop() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.DIAGNOSIS_START_DATE_REQUIRED); } // other input checks if (diagnosisIn.getStart() != null && diagnosisIn.getStop() != null && diagnosisIn.getStop().compareTo(diagnosisIn.getStart()) <= 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.DIAGNOSIS_END_DATE_LESS_THAN_OR_EQUAL_TO_START_DATE); } if ((new DiagnosisCollisionFinder(probandDao, this.getDiagnosisDao())).collides(diagnosisIn)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.DIAGNOSIS_OVERLAPPING); } } private void checkInquiryValueInput(InquiryValueInVO inquiryValueIn, Proband proband, Inquiry inquiry) throws ServiceException { InputFieldDao inputFieldDao = this.getInputFieldDao(); InputField inputField = inquiry.getField(); inputFieldDao.lock(inputField, LockMode.PESSIMISTIC_WRITE); ServiceUtil.checkInputFieldTextValue(inputField, inquiry.isOptional(), inquiryValueIn.getTextValue(), inputFieldDao, this.getInputFieldSelectionSetValueDao()); ServiceUtil.checkInputFieldBooleanValue(inputField, inquiry.isOptional(), inquiryValueIn.getBooleanValue(), inputFieldDao); ServiceUtil.checkInputFieldLongValue(inputField, inquiry.isOptional(), inquiryValueIn.getLongValue(), inputFieldDao); ServiceUtil.checkInputFieldFloatValue(inputField, inquiry.isOptional(), inquiryValueIn.getFloatValue(), inputFieldDao); ServiceUtil.checkInputFieldDateValue(inputField, inquiry.isOptional(), inquiryValueIn.getDateValue(), inputFieldDao); ServiceUtil.checkInputFieldTimeValue(inputField, inquiry.isOptional(), inquiryValueIn.getTimeValue(), inputFieldDao); ServiceUtil.checkInputFieldTimestampValue(inputField, inquiry.isOptional(), inquiryValueIn.getTimestampValue(), inputFieldDao); ServiceUtil.checkInputFieldInkValue(inputField, inquiry.isOptional(), inquiryValueIn.getInkValues(), inputFieldDao); ServiceUtil.checkInputFieldSelectionSetValues(inputField, inquiry.isOptional(), inquiryValueIn.getSelectionValueIds(), inputFieldDao, this.getInputFieldSelectionSetValueDao()); if ((new InquiryValueCollisionFinder(this.getProbandDao(), this.getInquiryValueDao())).collides(inquiryValueIn)) { throw L10nUtil .initServiceException(ServiceExceptionCodes.INQUIRY_VALUE_ALREADY_EXISTS, CommonUtil.inputFieldOutVOToString(inputFieldDao.toInputFieldOutVO(inputField))); } } private void checkMedicationInput(MedicationInVO medicationIn) throws ServiceException { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(medicationIn.getProbandId(), probandDao, LockMode.PESSIMISTIC_WRITE); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ServiceUtil.checkProbandLocked(proband); AspDao aspDao = this.getAspDao(); Asp asp = null; if (medicationIn.getAspId() != null) { asp = CheckIDUtil.checkAspId(medicationIn.getAspId(), aspDao); } AspSubstanceDao aspSubstanceDao = this.getAspSubstanceDao(); Collection<Long> substanceIds = medicationIn.getSubstanceIds(); if (substanceIds != null && substanceIds.size() > 0) { Iterator<Long> it = substanceIds.iterator(); HashSet<Long> dupeCheck = new HashSet<Long>(substanceIds.size()); HashSet<Long> aspSubstanceIds; Collection<AspSubstance> aspSubstances; if (asp != null && ((aspSubstances = asp.getSubstances()) != null) && aspSubstances.size() > 0) { aspSubstanceIds = new HashSet<Long>(aspSubstances.size()); Iterator<AspSubstance> aspSubstancesIt = aspSubstances.iterator(); while (aspSubstancesIt.hasNext()) { aspSubstanceIds.add(aspSubstancesIt.next().getId()); } } else { aspSubstanceIds = new HashSet<Long>(); } while (it.hasNext()) { Long id = it.next(); if (id == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_SUBSTANCE_ID_IS_NULL); } AspSubstance substance = CheckIDUtil.checkAspSubstanceId(id, aspSubstanceDao); if (!dupeCheck.add(substance.getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_DUPLICATE_SUBSTANCE, aspSubstanceDao.toAspSubstanceVO(substance).getName()); } if (asp != null && !aspSubstanceIds.remove(id)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_SUBSTANCE_NOT_CONTAINED, aspDao.toAspVO(asp).getName(), aspSubstanceDao.toAspSubstanceVO(substance).getName()); } } if (asp != null && aspSubstanceIds.size() > 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_SUBSTANCE_MISSING, aspDao.toAspVO(asp).getName(), ServiceUtil.aspSubstanceIDsToString(aspSubstanceIds, this.getAspSubstanceDao())); } } else { if (asp == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_SUBSTANCES_REQUIRED); } } Diagnosis diagnosis = null; if (medicationIn.getDiagnosisId() != null) { diagnosis = CheckIDUtil.checkDiagnosisId(medicationIn.getDiagnosisId(), this.getDiagnosisDao()); if (!proband.equals(diagnosis.getProband())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_WRONG_DIAGNOSIS, proband.getId().toString()); } } Procedure procedure = null; if (medicationIn.getProcedureId() != null) { procedure = CheckIDUtil.checkProcedureId(medicationIn.getProcedureId(), this.getProcedureDao()); if (!proband.equals(procedure.getProband())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_WRONG_PROCEDURE, proband.getId().toString()); } } if (medicationIn.getDoseValue() != null) { if (medicationIn.getDoseValue() <= 0.0f) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_DOSE_VALUE_LESS_THAN_OR_EQUAL_ZERO); } if (CommonUtil.isEmptyString(medicationIn.getDoseUnit())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_DOSE_UNIT_REQUIRED); } } else { if (medicationIn.getDoseUnit() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_DOSE_UNIT_NOT_NULL); } } if (medicationIn.getStart() == null && medicationIn.getStop() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_START_DATE_REQUIRED); } // other input checks if (medicationIn.getStart() != null && medicationIn.getStop() != null && medicationIn.getStop().compareTo(medicationIn.getStart()) <= 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_END_DATE_LESS_THAN_OR_EQUAL_TO_START_DATE); } if ((new MedicationCollisionFinder(probandDao, this.getMedicationDao())).collides(medicationIn)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_OVERLAPPING); } } private void checkMoneyTransferInput(MoneyTransferInVO moneyTransferIn, Long maxAllowedCostTypes) throws ServiceException { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(moneyTransferIn.getProbandId(), probandDao, LockMode.PESSIMISTIC_WRITE); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } if (!proband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PROBAND_NOT_PERSON); } ServiceUtil.checkProbandLocked(proband); if (moneyTransferIn.getTrialId() != null) { Trial trial = CheckIDUtil.checkTrialId(moneyTransferIn.getTrialId(), this.getTrialDao()); ServiceUtil.checkTrialLocked(trial); (new MaxCostTypesAdapter(maxAllowedCostTypes, this.getTrialDao(), this.getMoneyTransferDao())).checkCategoryInput(moneyTransferIn); } BankAccount bankAccount = null; if (moneyTransferIn.getBankAccountId() != null) { bankAccount = CheckIDUtil.checkBankAccountId(moneyTransferIn.getBankAccountId(), this.getBankAccountDao()); if (!proband.equals(bankAccount.getProband())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_WRONG_BANK_ACCOUNT, proband.getId().toString()); } } if (PaymentMethod.WIRE_TRANSFER.equals(moneyTransferIn.getMethod())) { if (bankAccount == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_BANK_ACCOUNT_REQUIRED); } } else { if (bankAccount != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_BANK_ACCOUNT_NOT_NULL); } if (moneyTransferIn.getReasonForPayment() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_REASON_FORM_PAYMENT_NOT_NULL); } if (moneyTransferIn.getReference() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_REFERENCE_NOT_NULL); } } if (PaymentMethod.VOUCHER.equals(moneyTransferIn.getMethod())) { if (moneyTransferIn.getAmount() < 0.0f) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_AMOUNT_NEGATIVE); } } else { if (moneyTransferIn.getVoucherCode() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_VOUCHER_CODE_NOT_NULL); } } if (moneyTransferIn.getShowComment() && CommonUtil.isEmptyString(moneyTransferIn.getComment())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_COMMENT_REQUIRED); } } private void checkParents(ProbandInVO probandIn, Proband child) throws ServiceException { Iterator<Proband> parentsIt = child.getParents().iterator(); int parentCount = 0; HashSet<Sex> parentGenders = new HashSet<Sex>(Sex.literals().size()); boolean isParent = false; while (parentsIt.hasNext()) { Proband parent = parentsIt.next(); if (parent.getId().equals(probandIn.getId())) { isParent = true; break; } if (parent.isPerson()) { ProbandContactParticulars personParticlars = parent.getPersonParticulars(); if (personParticlars != null && personParticlars.getGender() != null) { parentGenders.add(personParticlars.getGender()); } } else { AnimalContactParticulars animalParticlars = parent.getAnimalParticulars(); if (animalParticlars != null && animalParticlars.getGender() != null) { parentGenders.add(animalParticlars.getGender()); } } parentCount++; } if (!isParent) { ProbandDao probandDao = this.getProbandDao(); if (parentCount >= 2) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CHILD_TWO_PARENTS, child.getId().toString()); } if (probandIn.getGender() != null && !parentGenders.add(probandIn.getGender())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CHILD_PARENT_WITH_SAME_SEX, child.getId().toString(), L10nUtil.getSexName(Locales.USER, probandIn.getGender().name())); } } } private void checkProbandAddressInput(ProbandAddressInVO addressIn) throws ServiceException { (new ProbandAddressTypeTagAdapter(this.getProbandDao(), this.getAddressTypeDao())).checkTagValueInput(addressIn); } private void checkProbandContactDetailValueInput(ProbandContactDetailValueInVO contactValueIn) throws ServiceException { (new ProbandContactDetailTypeTagAdapter(this.getProbandDao(), this.getContactDetailTypeDao())).checkTagValueInput(contactValueIn); } private void checkProbandImageInput(ProbandImageInVO probandImage) throws ServiceException { if (probandImage.getDatas() != null && probandImage.getDatas().length > 0) { Integer probandImageSizeLimit = Settings.getIntNullable(SettingCodes.PROBAND_IMAGE_SIZE_LIMIT, Bundle.SETTINGS, DefaultSettings.PROBAND_IMAGE_SIZE_LIMIT); if (probandImageSizeLimit != null && probandImage.getDatas().length > probandImageSizeLimit) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_SIZE_LIMIT_EXCEEDED, CommonUtil.humanReadableByteCount(probandImageSizeLimit)); } if (probandImage.getMimeType() == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_MIME_TYPE_REQUIRED); } Iterator<MimeType> it = this.getMimeTypeDao().findByMimeTypeModule(probandImage.getMimeType(), FileModule.PROBAND_IMAGE).iterator(); if (!it.hasNext()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_MIME_TYPE_UNKNOWN, probandImage.getMimeType()); } if (!it.next().isImage()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_MIME_TYPE_NO_IMAGE, probandImage.getMimeType()); } Dimension imageDimension = CoreUtil.getImageDimension(probandImage.getDatas()); if (imageDimension == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_CANNOT_READ_DIMENSIONS); } else { Integer probandImageMinWidth = Settings.getIntNullable(SettingCodes.PROBAND_IMAGE_MIN_WIDTH, Bundle.SETTINGS, DefaultSettings.PROBAND_IMAGE_MIN_WIDTH); Integer probandImageMinHeight = Settings.getIntNullable(SettingCodes.PROBAND_IMAGE_MIN_HEIGHT, Bundle.SETTINGS, DefaultSettings.PROBAND_IMAGE_MIN_HEIGHT); if (probandImageMinWidth != null && imageDimension.getWidth() < (double) probandImageMinWidth) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_WIDTH_LESS_THAN_LIMIT, probandImageMinWidth); } if (probandImageMinHeight != null && imageDimension.getHeight() < (double) probandImageMinHeight) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_IMAGE_HEIGHT_LESS_THAN_LIMIT, probandImageMinHeight); } } } } private void checkProbandInput(ProbandInVO probandIn) throws ServiceException { // referential checks CheckIDUtil.checkDepartmentId(probandIn.getDepartmentId(), this.getDepartmentDao()); ProbandCategory category = CheckIDUtil.checkProbandCategoryId(probandIn.getCategoryId(), this.getProbandCategoryDao()); if (probandIn.getPhysicianId() != null) { CheckIDUtil.checkStaffId(probandIn.getPhysicianId(), this.getStaffDao()); } if (probandIn.getChildIds() != null && probandIn.getChildIds().size() > 0) { ProbandDao probandDao = this.getProbandDao(); ArrayList<Long> childIds = new ArrayList<Long>(probandIn.getChildIds()); Collections.sort(childIds); Iterator<Long> it = childIds.iterator(); HashSet<Long> dupeCheck = new HashSet<Long>(childIds.size()); while (it.hasNext()) { Long id = it.next(); if (id == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CHILD_NULL); } Proband child = CheckIDUtil.checkProbandId(id, probandDao, LockMode.PESSIMISTIC_WRITE); if (!dupeCheck.add(child.getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.DUPLICATE_PROBAND_CHILD, child.getId().toString()); } checkParents(probandIn, child); } } // other input checks if (probandIn.isPerson()) { if (!category.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CATEGORY_NOT_FOR_PERSON_ENTRIES, L10nUtil.getProbandCategoryName(Locales.USER, category.getNameL10nKey())); } if (!probandIn.isBlinded()) { if (CommonUtil.isEmptyString(probandIn.getFirstName())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_FIRST_NAME_REQUIRED); } if (CommonUtil.isEmptyString(probandIn.getLastName())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_LAST_NAME_REQUIRED); } if (probandIn.getDateOfBirth() == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DATE_OF_BIRTH_REQUIRED); } else if (DateCalc.getStartOfDay(probandIn.getDateOfBirth()).compareTo(new Date()) > 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DATE_OF_BIRTH_IN_THE_FUTURE); } if (probandIn.getGender() == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_GENDER_REQUIRED); } if (probandIn.getAlias() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_ALIAS_NOT_NULL); } } else { if (probandIn.getPrefixedTitle1() != null || probandIn.getPrefixedTitle2() != null || probandIn.getPrefixedTitle3() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_PREFIXED_TITLES_NOT_NULL); } if (probandIn.getFirstName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_FIRST_NAME_NOT_NULL); } if (probandIn.getLastName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_LAST_NAME_NOT_NULL); } if (probandIn.getDateOfBirth() != null && DateCalc.getStartOfDay(probandIn.getDateOfBirth()).compareTo(new Date()) > 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DATE_OF_BIRTH_IN_THE_FUTURE); } if (probandIn.getPostpositionedTitle1() != null || probandIn.getPostpositionedTitle2() != null || probandIn.getPostpositionedTitle3() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_POSTPOSITIONED_TITLES_NOT_NULL); } if (probandIn.getCitizenship() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CITIZENSHIP_NOT_NULL); } } if (probandIn.getAnimalName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ANIMAL_NAME_NOT_NULL); } } else { if (!category.isAnimal()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CATEGORY_NOT_FOR_ANIMAL_ENTRIES, L10nUtil.getProbandCategoryName(Locales.USER, category.getNameL10nKey())); } if (!probandIn.isBlinded()) { if (CommonUtil.isEmptyString(probandIn.getAnimalName())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ANIMAL_NAME_REQUIRED); } if (probandIn.getDateOfBirth() == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DATE_OF_BIRTH_REQUIRED); } else if (DateCalc.getStartOfDay(probandIn.getDateOfBirth()).compareTo(new Date()) > 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DATE_OF_BIRTH_IN_THE_FUTURE); } if (probandIn.getGender() == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_GENDER_REQUIRED); } if (probandIn.getAlias() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_ALIAS_NOT_NULL); } } else { if (probandIn.getAnimalName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.ANIMAL_NAME_NOT_NULL); } if (probandIn.getDateOfBirth() != null && DateCalc.getStartOfDay(probandIn.getDateOfBirth()).compareTo(new Date()) > 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DATE_OF_BIRTH_IN_THE_FUTURE); } } if (probandIn.getPrefixedTitle1() != null || probandIn.getPrefixedTitle2() != null || probandIn.getPrefixedTitle3() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_PREFIXED_TITLES_NOT_NULL); } if (probandIn.getFirstName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_FIRST_NAME_NOT_NULL); } if (probandIn.getLastName() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_LAST_NAME_NOT_NULL); } if (probandIn.getPostpositionedTitle1() != null || probandIn.getPostpositionedTitle2() != null || probandIn.getPostpositionedTitle3() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_POSTPOSITIONED_TITLES_NOT_NULL); } if (probandIn.getCitizenship() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CITIZENSHIP_NOT_NULL); } } if (probandIn.getRatingMax() != null) { if (probandIn.getRatingMax() <= 0l) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_RATING_MAX_LESS_THAN_OR_EQUAL_ZERO); } else if (probandIn.getRating() == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_RATING_REQUIRED); } else { if (probandIn.getRating() < 0l) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_RATING_LESS_THAN_ZERO); } else if (probandIn.getRating() > probandIn.getRatingMax()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_RATING_GREATER_THAN_RATING_MAX); } } } else if (probandIn.getRating() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_RATING_NOT_NULL); } } private void checkProbandLoop(Proband proband) throws ServiceException { (new ProbandReflexionGraph(this.getProbandDao())).checkGraphLoop(proband, false, true); } private void checkProbandStatusEntryInput(ProbandStatusEntryInVO statusEntryIn) throws ServiceException { ProbandDao probandDao = this.getProbandDao(); // referential checks Proband proband = CheckIDUtil.checkProbandId(statusEntryIn.getProbandId(), probandDao); ProbandStatusType statusType = CheckIDUtil.checkProbandStatusTypeId(statusEntryIn.getTypeId(), this.getProbandStatusTypeDao()); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ServiceUtil.checkProbandLocked(proband); if (proband.isPerson() && !statusType.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_STATUS_NOT_FOR_PERSON_ENTRIES, L10nUtil.getProbandStatusTypeName(Locales.USER, statusType.getNameL10nKey())); } if (!proband.isPerson() && !statusType.isAnimal()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_STATUS_NOT_FOR_ANIMAL_ENTRIES, L10nUtil.getProbandStatusTypeName(Locales.USER, statusType.getNameL10nKey())); } // other input checks if (statusEntryIn.getStop() != null && statusEntryIn.getStop().compareTo(statusEntryIn.getStart()) <= 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_STATUS_ENTRY_END_DATE_LESS_THAN_OR_EQUAL_TO_START_DATE); } if ((new ProbandStatusEntryCollisionFinder(probandDao, this.getProbandStatusEntryDao())).collides(statusEntryIn)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_STATUS_ENTRY_OVERLAPPING); } } private void checkProbandTagValueInput(ProbandTagValueInVO tagValueIn) throws ServiceException { (new ProbandTagAdapter(this.getProbandDao(), this.getProbandTagDao())).checkTagValueInput(tagValueIn); } private void checkProcedureInput(ProcedureInVO procedureIn) throws ServiceException { ProbandDao probandDao = this.getProbandDao(); // referential checks Proband proband = CheckIDUtil.checkProbandId(procedureIn.getProbandId(), probandDao); OpsCode opsCode = CheckIDUtil.checkOpsCodeId(procedureIn.getCodeId(), this.getOpsCodeDao()); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ServiceUtil.checkProbandLocked(proband); if (procedureIn.getStart() == null && procedureIn.getStop() != null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROCEDURE_START_DATE_REQUIRED); } // other input checks if (procedureIn.getStart() != null && procedureIn.getStop() != null && procedureIn.getStop().compareTo(procedureIn.getStart()) <= 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROCEDURE_END_DATE_LESS_THAN_OR_EQUAL_TO_START_DATE); } if ((new ProcedureCollisionFinder(probandDao, this.getProcedureDao())).collides(procedureIn)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROCEDURE_OVERLAPPING); } } private InquiryValuesOutVO getInquiryValues(Trial trial, String category, ProbandOutVO probandVO, Boolean active, Boolean activeSignup, boolean jsValues, boolean loadAllJsValues, boolean sort, PSFVO psf) throws Exception { InquiryValueDao inquiryValueDao = this.getInquiryValueDao(); InquiryValuesOutVO result = new InquiryValuesOutVO(); Collection<Map> inquiryValues = inquiryValueDao.findByProbandTrialCategoryActiveJs(probandVO.getId(), trial.getId(), category, active, activeSignup, sort, null, psf); result.setPageValues(ServiceUtil.getInquiryValues(probandVO, inquiryValues, null, this.getInquiryDao(), inquiryValueDao)); if (jsValues) { if (loadAllJsValues) { result.setJsValues(ServiceUtil.getInquiryJsonValues( inquiryValueDao.findByProbandTrialActiveJs(probandVO.getId(), trial.getId(), active, activeSignup, sort, true, null), false, inquiryValueDao, this.getInputFieldSelectionSetValueDao())); } else { result.setJsValues(ServiceUtil.getInquiryJsonValues(inquiryValues, true, inquiryValueDao, this.getInputFieldSelectionSetValueDao())); } } return result; } @Override protected BankAccountOutVO handleAddBankAccount( AuthenticationVO auth, BankAccountInVO newBankAccount) throws Exception { checkBankAccountInput(newBankAccount); BankAccountDao bankAccountDao = this.getBankAccountDao(); BankAccount bankAccount = bankAccountDao.bankAccountInVOToEntity(newBankAccount); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(bankAccount, now, user); bankAccount = bankAccountDao.create(bankAccount); BankAccountOutVO result = bankAccountDao.toBankAccountOutVO(bankAccount); ServiceUtil.logSystemMessage(bankAccount.getProband(), result.getProband(), now, user, SystemMessageCodes.BANK_ACCOUNT_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected DiagnosisOutVO handleAddDiagnosis(AuthenticationVO auth, DiagnosisInVO newDiagnosis) throws Exception { checkDiagnosisInput(newDiagnosis); DiagnosisDao diagnosisDao = this.getDiagnosisDao(); Diagnosis diagnosis = diagnosisDao.diagnosisInVOToEntity(newDiagnosis); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(diagnosis, now, user); diagnosis = diagnosisDao.create(diagnosis); DiagnosisOutVO result = diagnosisDao.toDiagnosisOutVO(diagnosis); ServiceUtil.logSystemMessage(diagnosis.getProband(), result.getProband(), now, user, SystemMessageCodes.DIAGNOSIS_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected MedicationOutVO handleAddMedication(AuthenticationVO auth, MedicationInVO newMedication) throws Exception { checkMedicationInput(newMedication); MedicationDao medicationDao = this.getMedicationDao(); Medication medication = medicationDao.medicationInVOToEntity(newMedication); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(medication, now, user); medication = medicationDao.create(medication); MedicationOutVO result = medicationDao.toMedicationOutVO(medication); ServiceUtil.logSystemMessage(medication.getProband(), result.getProband(), now, user, SystemMessageCodes.MEDICATION_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected MoneyTransferOutVO handleAddMoneyTransfer( AuthenticationVO auth, MoneyTransferInVO newMoneyTransfer, Long maxAllowedCostTypes) throws Exception { checkMoneyTransferInput(newMoneyTransfer, maxAllowedCostTypes); MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); MoneyTransfer moneyTransfer = moneyTransferDao.moneyTransferInVOToEntity(newMoneyTransfer); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(moneyTransfer, now, user); moneyTransfer = moneyTransferDao.create(moneyTransfer); Trial trial = moneyTransfer.getTrial(); MoneyTransferOutVO result = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); if (trial != null) { logSystemMessage(trial, result.getProband(), now, user, SystemMessageCodes.MONEY_TRANSFER_CREATED, result, null, this.getJournalEntryDao()); } ServiceUtil .logSystemMessage(moneyTransfer.getProband(), result.getProband(), now, user, SystemMessageCodes.MONEY_TRANSFER_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandOutVO handleAddProband(AuthenticationVO auth, ProbandInVO newProband, Integer maxInstances, Integer maxParentsDepth, Integer maxChildrenDepth) throws Exception { checkProbandInput(newProband); User user = CoreUtil.getUser(); this.getUserDao().lock(user, LockMode.PESSIMISTIC_WRITE); if (!user.getDepartment().getId().equals(newProband.getDepartmentId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DEPARTMENT_NOT_EQUAL_TO_USER_DEPARTMENT); } Timestamp now = new Timestamp(System.currentTimeMillis()); Proband proband = ServiceUtil.createProband(newProband, now, user, this.getProbandDao(), this.getPrivacyConsentStatusTypeDao(), this.getProbandContactParticularsDao(), this.getAnimalContactParticularsDao(), this.getNotificationDao()); ProbandOutVO result = this.getProbandDao().toProbandOutVO(proband, maxInstances, maxParentsDepth, maxChildrenDepth); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PROBAND_CREATED, result, null, journalEntryDao); Staff physician = proband.getPhysician(); if (physician != null) { ServiceUtil.logSystemMessage(physician, result, now, user, SystemMessageCodes.PROBAND_CREATED, result, null, journalEntryDao); } return result; } @Override protected ProbandAddressOutVO handleAddProbandAddress( AuthenticationVO auth, ProbandAddressInVO newProbandAddress) throws Exception { checkProbandAddressInput(newProbandAddress); ProbandAddressDao addressDao = this.getProbandAddressDao(); ProbandAddress address = addressDao.probandAddressInVOToEntity(newProbandAddress); if (addressDao.getCount(address.getProband().getId(), null, null, true) == 0) { address.setWireTransfer(true); } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(address, now, user); address = addressDao.create(address); ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address); ServiceUtil.logSystemMessage(address.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandContactDetailValueOutVO handleAddProbandContactDetailValue( AuthenticationVO auth, ProbandContactDetailValueInVO newProbandContactDetailValue) throws Exception { checkProbandContactDetailValueInput(newProbandContactDetailValue); ProbandContactDetailValueDao contactValueDao = this.getProbandContactDetailValueDao(); ProbandContactDetailValue contactValue = contactValueDao.probandContactDetailValueInVOToEntity(newProbandContactDetailValue); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(contactValue, now, user); contactValue = contactValueDao.create(contactValue); ProbandContactDetailValueOutVO result = contactValueDao.toProbandContactDetailValueOutVO(contactValue); ServiceUtil.logSystemMessage(contactValue.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_CONTACT_DETAIL_VALUE_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandStatusEntryOutVO handleAddProbandStatusEntry( AuthenticationVO auth, ProbandStatusEntryInVO newProbandStatusEntry) throws Exception { checkProbandStatusEntryInput(newProbandStatusEntry); ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); ProbandStatusEntry statusEntry = statusEntryDao.probandStatusEntryInVOToEntity(newProbandStatusEntry); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(statusEntry, now, user); statusEntry = statusEntryDao.create(statusEntry); notifyProbandInactive(statusEntry, now); ProbandStatusEntryOutVO result = statusEntryDao.toProbandStatusEntryOutVO(statusEntry); ServiceUtil.logSystemMessage(statusEntry.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_STATUS_ENTRY_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandTagValueOutVO handleAddProbandTagValue( AuthenticationVO auth, ProbandTagValueInVO newProbandTagValue) throws Exception { checkProbandTagValueInput(newProbandTagValue); ProbandTagValueDao tagValueDao = this.getProbandTagValueDao(); ProbandTagValue tagValue = tagValueDao.probandTagValueInVOToEntity(newProbandTagValue); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(tagValue, now, user); tagValue = tagValueDao.create(tagValue); ProbandTagValueOutVO result = tagValueDao.toProbandTagValueOutVO(tagValue); ServiceUtil.logSystemMessage(tagValue.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_TAG_VALUE_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProcedureOutVO handleAddProcedure(AuthenticationVO auth, ProcedureInVO newProcedure) throws Exception { checkProcedureInput(newProcedure); ProcedureDao procedureDao = this.getProcedureDao(); Procedure procedure = procedureDao.procedureInVOToEntity(newProcedure); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(procedure, now, user); procedure = procedureDao.create(procedure); ProcedureOutVO result = procedureDao.toProcedureOutVO(procedure); ServiceUtil.logSystemMessage(procedure.getProband(), result.getProband(), now, user, SystemMessageCodes.PROCEDURE_CREATED, result, null, this.getJournalEntryDao()); return result; } @Override protected Collection<String> handleCompleteCostTypes(AuthenticationVO auth, Long trialDepartmentId, Long trialId, Long probandDepartmentId, Long probandId, String costTypePrefix, Integer limit) throws Exception { if (trialDepartmentId != null) { CheckIDUtil.checkDepartmentId(trialDepartmentId, this.getDepartmentDao()); } if (probandDepartmentId != null) { CheckIDUtil.checkDepartmentId(probandDepartmentId, this.getDepartmentDao()); } if (trialId != null) { CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); } if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getMoneyTransferDao().findCostTypes(trialDepartmentId, trialId, probandDepartmentId, probandId, costTypePrefix, limit); } @Override protected BankAccountOutVO handleDeleteBankAccount(AuthenticationVO auth, Long bankAccountId) throws Exception { BankAccountDao bankAccountDao = this.getBankAccountDao(); BankAccount bankAccount = CheckIDUtil.checkBankAccountId(bankAccountId, bankAccountDao); Proband proband = bankAccount.getProband(); BankAccountOutVO result = bankAccountDao.toBankAccountOutVO(bankAccount); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_BANK_ACCOUNT); } ServiceUtil.checkProbandLocked(proband); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); proband.removeBankAccounts(bankAccount); bankAccount.setProband(null); MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); Iterator<MoneyTransfer> moneyTransfersIt = bankAccount.getMoneyTransfers().iterator(); while (moneyTransfersIt.hasNext()) { MoneyTransfer moneyTransfer = moneyTransfersIt.next(); MoneyTransferOutVO moneyTransferVO = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); Trial trial = moneyTransfer.getTrial(); if (trial != null) { ServiceUtil.checkTrialLocked(trial); logSystemMessage(trial, result.getProband(), now, user, SystemMessageCodes.BANK_ACCOUNT_DELETED_MONEY_TRANSFER_DELETED, moneyTransferVO, null, journalEntryDao); trial.removePayoffs(moneyTransfer); } moneyTransfer.setBankAccount(null); moneyTransferDao.remove(moneyTransfer); moneyTransfer.setProband(null); proband.removeMoneyTransfers(moneyTransfer); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.BANK_ACCOUNT_DELETED_MONEY_TRANSFER_DELETED, moneyTransferVO, null, journalEntryDao); } bankAccount.getMoneyTransfers().clear(); bankAccountDao.remove(bankAccount); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.BANK_ACCOUNT_DELETED, result, null, journalEntryDao); return result; } @Override protected DiagnosisOutVO handleDeleteDiagnosis(AuthenticationVO auth, Long diagnosisId) throws Exception { DiagnosisDao diagnosisDao = this.getDiagnosisDao(); Diagnosis diagnosis = CheckIDUtil.checkDiagnosisId(diagnosisId, diagnosisDao); Proband proband = diagnosis.getProband(); DiagnosisOutVO result = diagnosisDao.toDiagnosisOutVO(diagnosis); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_DIAGNOSIS); } ServiceUtil.checkProbandLocked(proband); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); AlphaId alphaId = diagnosis.getCode(); alphaId.removeDiagnoses(diagnosis); diagnosis.setCode(null); proband.removeDiagnoses(diagnosis); diagnosis.setProband(null); MedicationDao medicationDao = this.getMedicationDao(); Iterator<Medication> medicationsIt = diagnosis.getMedications().iterator(); while (medicationsIt.hasNext()) { Medication medication = medicationsIt.next(); MedicationOutVO originalMedicationVO = medicationDao.toMedicationOutVO(medication); medication.setDiagnosis(null); CoreUtil.modifyVersion(medication, medication.getVersion(), now, user); medicationDao.update(medication); MedicationOutVO medicationVO = medicationDao.toMedicationOutVO(medication); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.DIAGNOSIS_DELETED_MEDICATION_UPDATED, medicationVO, originalMedicationVO, journalEntryDao); } diagnosis.getMedications().clear(); diagnosisDao.remove(diagnosis); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.DIAGNOSIS_DELETED, result, null, journalEntryDao); return result; } @Override protected MedicationOutVO handleDeleteMedication(AuthenticationVO auth, Long medicationId) throws Exception { MedicationDao medicationDao = this.getMedicationDao(); Medication medication = CheckIDUtil.checkMedicationId(medicationId, medicationDao); Proband proband = medication.getProband(); MedicationOutVO result = medicationDao.toMedicationOutVO(medication); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_MEDICATION); } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); Diagnosis diagnosis = medication.getDiagnosis(); Procedure procedure = medication.getProcedure(); proband.removeMedications(medication); medication.setProband(null); if (diagnosis != null) { diagnosis.removeMedications(medication); medication.setDiagnosis(null); } if (procedure != null) { procedure.removeMedications(medication); medication.setProcedure(null); } medicationDao.remove(medication); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.MEDICATION_DELETED, result, null, this.getJournalEntryDao()); return result; } @Override protected MoneyTransferOutVO handleDeleteMoneyTransfer(AuthenticationVO auth, Long moneyTransferId) throws Exception { MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); MoneyTransfer moneyTransfer = CheckIDUtil.checkMoneyTransferId(moneyTransferId, moneyTransferDao); Proband proband = moneyTransfer.getProband(); MoneyTransferOutVO result = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_MONEY_TRANSFER); } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); BankAccount bankAccount = moneyTransfer.getBankAccount(); Trial trial = moneyTransfer.getTrial(); if (trial != null) { ServiceUtil.checkTrialLocked(trial); trial.removePayoffs(moneyTransfer); moneyTransfer.setTrial(null); } proband.removeMoneyTransfers(moneyTransfer); moneyTransfer.setProband(null); if (bankAccount != null) { bankAccount.removeMoneyTransfers(moneyTransfer); moneyTransfer.setBankAccount(null); } moneyTransferDao.remove(moneyTransfer); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); if (trial != null) { logSystemMessage(trial, result.getProband(), now, user, SystemMessageCodes.MONEY_TRANSFER_DELETED, result, null, journalEntryDao); } ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.MONEY_TRANSFER_DELETED, result, null, journalEntryDao); return result; } @Override protected ProbandOutVO handleDeleteProband(AuthenticationVO auth, Long probandId, boolean defer, boolean force, String deferredDeleteReason, Integer maxInstances, Integer maxParentsDepth, Integer maxChildrenDepth) throws Exception { ProbandDao probandDao = this.getProbandDao(); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); ProbandOutVO result; if (!force && defer) { Proband originalProband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO original = probandDao.toProbandOutVO(originalProband, maxInstances, maxParentsDepth, maxChildrenDepth); if (original.getBlinded()) { if (!user.getDepartment().getId().equals(originalProband.getDepartment().getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DEPARTMENT_NOT_EQUAL_TO_USER_DEPARTMENT); } } else { if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } } probandDao.evict(originalProband); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao, LockMode.PESSIMISTIC_WRITE); if (CommonUtil.isEmptyString(deferredDeleteReason)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.DEFERRED_DELETE_REASON_REQUIRED); } proband.setDeferredDelete(true); proband.setDeferredDeleteReason(deferredDeleteReason); CoreUtil.modifyVersion(proband, proband.getVersion(), now, user); // no opt. locking probandDao.update(proband); result = probandDao.toProbandOutVO(proband, maxInstances, maxParentsDepth, maxChildrenDepth); ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PROBAND_MARKED_FOR_DELETION, result, original, journalEntryDao); Iterator<ProbandOutVO> parentsIt = original.getParents().iterator(); while (parentsIt.hasNext()) { ProbandOutVO parent = parentsIt.next(); ServiceUtil.logSystemMessage(probandDao.load(parent.getId()), result, now, user, SystemMessageCodes.PROBAND_MARKED_FOR_DELETION, result, original, journalEntryDao); } } else { Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao, LockMode.PESSIMISTIC_WRITE); result = probandDao.toProbandOutVO(proband, maxInstances, maxParentsDepth, maxChildrenDepth); if (result.getBlinded()) { if (!user.getDepartment().getId().equals(result.getDepartment().getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DEPARTMENT_NOT_EQUAL_TO_USER_DEPARTMENT); } } else { if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } } ServiceUtil.removeProband(proband, result, true, user, now, this.getProbandDao(), this.getProbandContactParticularsDao(), this.getAnimalContactParticularsDao(), journalEntryDao, this.getNotificationDao(), this.getNotificationRecipientDao(), this.getProbandTagValueDao(), this.getProbandContactDetailValueDao(), this.getProbandAddressDao(), this.getProbandStatusEntryDao(), this.getDiagnosisDao(), this.getProcedureDao(), this.getMedicationDao(), this.getInventoryBookingDao(), this.getMoneyTransferDao(), this.getBankAccountDao(), this.getProbandListStatusEntryDao(), this.getProbandListEntryDao(), this.getProbandListEntryTagValueDao(), this.getInputFieldValueDao(), this.getInquiryValueDao(), this.getECRFFieldValueDao(), this.getECRFFieldStatusEntryDao(), this.getSignatureDao(), this.getECRFStatusEntryDao(), this.getMassMailRecipientDao(), this.getJobDao(), this.getFileDao()); } return result; } @Override protected ProbandAddressOutVO handleDeleteProbandAddress( AuthenticationVO auth, Long probandAddressId) throws Exception { ProbandAddressDao addressDao = this.getProbandAddressDao(); ProbandAddress address = CheckIDUtil.checkProbandAddressId(probandAddressId, addressDao); Proband proband = address.getProband(); this.getProbandDao().lock(proband, LockMode.PESSIMISTIC_WRITE); ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_ADDRESS); } ServiceUtil.checkProbandLocked(proband); if (address.isWireTransfer() && addressDao.getCount(address.getProband().getId(), null, null, null) > 1) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DELETE_WIRE_TRANSFER_PROBAND_ADDRESS); } proband.removeAddresses(address); address.setProband(null); addressDao.remove(address); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_DELETED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandContactDetailValueOutVO handleDeleteProbandContactDetailValue( AuthenticationVO auth, Long probandContactDetailValueId) throws Exception { ProbandContactDetailValueDao contactValueDao = this.getProbandContactDetailValueDao(); ProbandContactDetailValue contactValue = CheckIDUtil.checkProbandContactDetailValueId(probandContactDetailValueId, contactValueDao); Proband proband = contactValue.getProband(); ProbandContactDetailValueOutVO result = contactValueDao.toProbandContactDetailValueOutVO(contactValue); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_CONTACT_DETAIL_VALUE); } ServiceUtil.checkProbandLocked(proband); proband.removeContactDetailValues(contactValue); contactValue.setProband(null); contactValueDao.remove(contactValue); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_CONTACT_DETAIL_VALUE_DELETED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandStatusEntryOutVO handleDeleteProbandStatusEntry( AuthenticationVO auth, Long probandStatusEntryId) throws Exception { ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); ProbandStatusEntry statusEntry = CheckIDUtil.checkProbandStatusEntryId(probandStatusEntryId, statusEntryDao); Proband proband = statusEntry.getProband(); ProbandStatusEntryOutVO result = statusEntryDao.toProbandStatusEntryOutVO(statusEntry); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_STATUS_ENTRY); } ServiceUtil.checkProbandLocked(proband); proband.removeStatusEntries(statusEntry); statusEntry.setProband(null); ServiceUtil.removeNotifications(statusEntry.getNotifications(), this.getNotificationDao(), this.getNotificationRecipientDao()); statusEntryDao.remove(statusEntry); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_STATUS_ENTRY_DELETED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandTagValueOutVO handleDeleteProbandTagValue(AuthenticationVO auth, Long probandTagValueId) throws Exception { ProbandTagValueDao tagValueDao = this.getProbandTagValueDao(); ProbandTagValue tagValue = CheckIDUtil.checkProbandTagValueId(probandTagValueId, tagValueDao); Proband proband = tagValue.getProband(); ProbandTagValueOutVO result = tagValueDao.toProbandTagValueOutVO(tagValue); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_TAG_VALUE); } ServiceUtil.checkProbandLocked(proband); proband.removeTagValues(tagValue); tagValue.setProband(null); tagValueDao.remove(tagValue); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_TAG_VALUE_DELETED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProcedureOutVO handleDeleteProcedure(AuthenticationVO auth, Long procedureId) throws Exception { ProcedureDao procedureDao = this.getProcedureDao(); Procedure procedure = CheckIDUtil.checkProcedureId(procedureId, procedureDao); Proband proband = procedure.getProband(); ProcedureOutVO result = procedureDao.toProcedureOutVO(procedure); if (!result.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROCEDURE); } ServiceUtil.checkProbandLocked(proband); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); OpsCode opsCode = procedure.getCode(); opsCode.removeProcedures(procedure); procedure.setCode(null); proband.removeProcedures(procedure); procedure.setProband(null); MedicationDao medicationDao = this.getMedicationDao(); Iterator<Medication> medicationsIt = procedure.getMedications().iterator(); while (medicationsIt.hasNext()) { Medication medication = medicationsIt.next(); MedicationOutVO originalMedicationVO = medicationDao.toMedicationOutVO(medication); medication.setProcedure(null); CoreUtil.modifyVersion(medication, medication.getVersion(), now, user); medicationDao.update(medication); MedicationOutVO medicationVO = medicationDao.toMedicationOutVO(medication); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROCEDURE_DELETED_MEDICATION_UPDATED, medicationVO, originalMedicationVO, journalEntryDao); } procedure.getMedications().clear(); procedureDao.remove(procedure); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROCEDURE_DELETED, result, null, journalEntryDao); return result; } @Override protected ReimbursementsExcelVO handleExportReimbursements( AuthenticationVO auth, Long probandId, String costType, PaymentMethod method, Boolean paid) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); if (!proband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PROBAND_NOT_PERSON); } ProbandOutVO probandVO = probandDao.toProbandOutVO(proband); MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); Collection<String> costTypes = moneyTransferDao.getCostTypes(null, null, null, probandVO.getId(), method); Collection<MoneyTransfer> moneyTransfers = moneyTransferDao.findByProbandTrialMethodCostTypePaidPerson(null, null, null, probandVO.getId(), method, costType, paid, null, null); ReimbursementsExcelVO result = ServiceUtil.createReimbursementsExcel(moneyTransfers, costTypes, null, probandVO, costType, method, paid, moneyTransferDao, this.getBankAccountDao(), this.getProbandAddressDao(), this.getAddressTypeDao(), this.getUserDao()); ServiceUtil.logSystemMessage(proband, result.getProband(), CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.REIMBURSEMENTS_EXPORTED, result, null, this.getJournalEntryDao()); return result; } @Override protected VisitScheduleExcelVO handleExportVisitSchedule( AuthenticationVO auth, Long probandId, Long trialId) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO probandVO = probandDao.toProbandOutVO(proband); TrialDao trialDao = this.getTrialDao(); TrialOutVO trialVO = null; if (trialId != null) { trialVO = trialDao.toTrialOutVO(CheckIDUtil.checkTrialId(trialId, trialDao)); } VisitScheduleExcelWriter.Styles style = trialVO == null ? VisitScheduleExcelWriter.Styles.PROBAND_VISIT_SCHEDULE : VisitScheduleExcelWriter.Styles.PROBAND_TRIAL_VISIT_SCHEDULE; VisitScheduleItemDao visitScheduleItemDao = this.getVisitScheduleItemDao(); Collection<VisitScheduleItem> visitScheduleItems; switch (style) { case PROBAND_VISIT_SCHEDULE: visitScheduleItems = visitScheduleItemDao.findByTrialGroupVisitProbandTravel(null, null, null, probandVO.getId(), null, true, null); break; case PROBAND_TRIAL_VISIT_SCHEDULE: visitScheduleItems = visitScheduleItemDao.findByTrialGroupVisitProbandTravel(trialVO.getId(), null, null, probandVO.getId(), null, true, null); break; default: visitScheduleItems = null; } VisitScheduleExcelVO result = ServiceUtil.createVisitScheduleExcel(visitScheduleItems, style, probandVO, trialVO, visitScheduleItemDao, this.getProbandListStatusEntryDao(), this.getProbandAddressDao(), this.getUserDao()); switch (style) { case PROBAND_VISIT_SCHEDULE: ServiceUtil.logSystemMessage(proband, result.getProband(), CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.VISIT_SCHEDULE_EXPORTED, result, null, this.getJournalEntryDao()); break; case PROBAND_TRIAL_VISIT_SCHEDULE: ServiceUtil.logSystemMessage(proband, trialVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.VISIT_SCHEDULE_EXPORTED, result, null, this.getJournalEntryDao()); break; default: } return result; } @Override protected Collection<ProbandOutVO> handleGetAutoDeletionProbands( AuthenticationVO auth, Date today, Long departmentId, Long probandCategoryId, VariablePeriod reminderPeriod, Long reminderPeriodDays, PSFVO psf) throws Exception { if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } if (probandCategoryId != null) { CheckIDUtil.checkProbandCategoryId(probandCategoryId, this.getProbandCategoryDao()); } ServiceUtil.checkReminderPeriod(reminderPeriod, reminderPeriodDays); ProbandDao probandDao = this.getProbandDao(); Collection autoDeletionProbands = probandDao.findToBeAutoDeleted(today, departmentId, probandCategoryId, reminderPeriod, reminderPeriodDays, null, true, psf); probandDao.toProbandOutVOCollection(autoDeletionProbands); return autoDeletionProbands; } @Override protected BankAccountOutVO handleGetBankAccount(AuthenticationVO auth, Long bankAccountId) throws Exception { BankAccountDao bankAccountDao = this.getBankAccountDao(); BankAccount bankAccount = CheckIDUtil.checkBankAccountId(bankAccountId, bankAccountDao); BankAccountOutVO result = bankAccountDao.toBankAccountOutVO(bankAccount); return result; } @Override protected long handleGetBankAccountCount(AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getBankAccountDao().getCount(probandId); } @Override protected Collection<BankAccountOutVO> handleGetBankAccountList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } BankAccountDao bankAccountDao = this.getBankAccountDao(); Collection bankAccounts = bankAccountDao.findByProband(probandId, null, null, psf); bankAccountDao.toBankAccountOutVOCollection(bankAccounts); return bankAccounts; } @Override protected Collection<BankAccountOutVO> handleGetBankAccounts( AuthenticationVO auth, Long probandId, Boolean active, Long bankAccountId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } BankAccountDao bankAccountDao = this.getBankAccountDao(); if (bankAccountId != null) { CheckIDUtil.checkBankAccountId(bankAccountId, bankAccountDao); } Collection bankAccounts = bankAccountDao.findByProbandActiveId(probandId, active, bankAccountId); bankAccountDao.toBankAccountOutVOCollection(bankAccounts); return bankAccounts; } @Override protected Collection<InventoryBookingOutVO> handleGetCollidingProbandInventoryBookings( AuthenticationVO auth, Long probandStatusEntryId, Boolean isRelevantForProbandAppointments) throws Exception { ProbandStatusEntry probandStatus = CheckIDUtil.checkProbandStatusEntryId(probandStatusEntryId, this.getProbandStatusEntryDao()); Collection collidingInventoryBookings; if (!probandStatus.getType().isProbandActive()) { InventoryBookingDao inventoryBookingDao = this.getInventoryBookingDao(); collidingInventoryBookings = inventoryBookingDao.findByProbandCalendarInterval(probandStatus.getProband().getId(), null, probandStatus.getStart(), probandStatus.getStop(), isRelevantForProbandAppointments); inventoryBookingDao.toInventoryBookingOutVOCollection(collidingInventoryBookings); } else { collidingInventoryBookings = new ArrayList<InventoryBookingOutVO>(); } return collidingInventoryBookings; } @Override protected Collection<VisitScheduleItemOutVO> handleGetCollidingVisitScheduleItems( AuthenticationVO auth, Long probandStatusEntryId, boolean allProbandGroups) throws Exception { ProbandStatusEntry probandStatusEntry = CheckIDUtil.checkProbandStatusEntryId(probandStatusEntryId, this.getProbandStatusEntryDao()); if (!probandStatusEntry.getType().isProbandActive()) { Collection collidingVisitScheduleItems = new HashSet(); VisitScheduleItemDao visitScheduleItemDao = this.getVisitScheduleItemDao(); Iterator<ProbandListEntry> trialParticipationsIt = probandStatusEntry.getProband().getTrialParticipations().iterator(); while (trialParticipationsIt.hasNext()) { ProbandListEntry probandListEntry = trialParticipationsIt.next(); ProbandGroup probandGroup = probandListEntry.getGroup(); if (probandGroup != null) { collidingVisitScheduleItems .addAll(visitScheduleItemDao.findByInterval(probandListEntry.getTrial().getId(), probandGroup.getId(), probandListEntry.getProband().getId(), probandStatusEntry.getStart(), probandStatusEntry.getStop())); } else { if (allProbandGroups) { collidingVisitScheduleItems.addAll( visitScheduleItemDao.findByInterval(probandListEntry.getTrial().getId(), null, probandListEntry.getProband().getId(), probandStatusEntry.getStart(), probandStatusEntry.getStop())); } } } visitScheduleItemDao.toVisitScheduleItemOutVOCollection(collidingVisitScheduleItems); return new ArrayList<VisitScheduleItemOutVO>(collidingVisitScheduleItems); } else { return new ArrayList<VisitScheduleItemOutVO>(); } } @Override protected Collection<String> handleGetCostTypes(AuthenticationVO auth, Long trialDepartmentId, Long trialId, Long probandDepartmentId, Long probandId, PaymentMethod method) throws Exception { if (trialDepartmentId != null) { CheckIDUtil.checkDepartmentId(trialDepartmentId, this.getDepartmentDao()); } if (probandDepartmentId != null) { CheckIDUtil.checkDepartmentId(probandDepartmentId, this.getDepartmentDao()); } if (trialId != null) { CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); } if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getMoneyTransferDao().getCostTypes(trialDepartmentId, trialId, probandDepartmentId, probandId, method); } @Override protected DiagnosisOutVO handleGetDiagnosis(AuthenticationVO auth, Long diagnosisId) throws Exception { DiagnosisDao diagnosisDao = this.getDiagnosisDao(); Diagnosis diagnosis = CheckIDUtil.checkDiagnosisId(diagnosisId, diagnosisDao); DiagnosisOutVO result = diagnosisDao.toDiagnosisOutVO(diagnosis); return result; } @Override protected long handleGetDiagnosisCount( AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getDiagnosisDao().getCount(probandId); } @Override protected Collection<DiagnosisOutVO> handleGetDiagnosisList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } DiagnosisDao diagnosisDao = this.getDiagnosisDao(); Collection diagnoses = diagnosisDao.findByProband(probandId, psf); diagnosisDao.toDiagnosisOutVOCollection(diagnoses); return diagnoses; } @Override protected long handleGetInquiryCount(AuthenticationVO auth, Long trialId, Boolean active, Boolean activeSignup) throws Exception { if (trialId != null) { CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); } return this.getInquiryDao().getCount(trialId, active, activeSignup); } @Override protected long handleGetInquiryCount(AuthenticationVO auth, Long trialId, String category, Boolean active, Boolean activeSignup) throws Exception { if (trialId != null) { CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); } return this.getInquiryDao().getCount(trialId, category, active, activeSignup); } @Override protected Collection<InquiryValueOutVO> handleGetInquiryInputFieldValues( AuthenticationVO auth, Long trialId, Boolean active, Boolean activeSignup, Long probandId, Long inputFieldId) throws Exception { if (trialId != null) { CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); } CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); CheckIDUtil.checkInputFieldId(inputFieldId, this.getInputFieldDao()); InquiryValueDao inquiryValueDao = this.getInquiryValueDao(); Collection inquiryFieldValues = inquiryValueDao.findByTrialActiveProbandField(trialId, active, activeSignup, probandId, inputFieldId); inquiryValueDao.toInquiryValueOutVOCollection(inquiryFieldValues); return inquiryFieldValues; } @Override protected Collection<TrialOutVO> handleGetInquiryTrials(AuthenticationVO auth, Long probandId, Boolean active, Boolean activeSignup) throws Exception { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); TrialDao trialDao = this.getTrialDao(); Collection trials = trialDao.findByInquiryValuesProbandSorted(null, probandId, active, activeSignup); trialDao.toTrialOutVOCollection(trials); return trials; } @Override protected InquiryValuesOutVO handleGetInquiryValue(AuthenticationVO auth, Long probandId, Long inquiryId) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); InquiryDao inquiryDao = this.getInquiryDao(); Inquiry inquiry = CheckIDUtil.checkInquiryId(inquiryId, inquiryDao); InquiryValueDao inquiryValueDao = this.getInquiryValueDao(); InquiryValuesOutVO result = new InquiryValuesOutVO(); Iterator<InquiryValue> it = inquiryValueDao.findByProbandInquiry(probandId, inquiryId).iterator(); if (it.hasNext()) { InquiryValue inquiryValue = it.next(); result.getPageValues().add(inquiryValueDao.toInquiryValueOutVO(inquiryValue)); if (!CommonUtil.isEmptyString(inquiryValue.getInquiry().getJsVariableName()) && Settings.getBoolean(SettingCodes.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION, Bundle.SETTINGS, DefaultSettings.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION)) { result.getJsValues().add(inquiryValueDao.toInquiryValueJsonVO(inquiryValue)); } } else { result.getPageValues().add( ServiceUtil.createPresetInquiryOutValue(probandDao.toProbandOutVO(proband), inquiryDao.toInquiryOutVO(inquiry), null)); if (!CommonUtil.isEmptyString(inquiry.getJsVariableName()) && Settings.getBoolean(SettingCodes.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION, Bundle.SETTINGS, DefaultSettings.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION)) { result.getJsValues().add(ServiceUtil.createPresetInquiryJsonValue(inquiry, this.getInputFieldSelectionSetValueDao())); } } return result; } @Override protected InquiryValueOutVO handleGetInquiryValueById(AuthenticationVO auth, Long inquiryValueId) throws Exception { InquiryValueDao inquiryValueDao = this.getInquiryValueDao(); return inquiryValueDao.toInquiryValueOutVO(CheckIDUtil.checkInquiryValueId(inquiryValueId, inquiryValueDao)); } @Override protected long handleGetInquiryValueCount(AuthenticationVO auth, Long trialId, Boolean active, Boolean activeSignup, Long probandId) throws Exception { Trial trial = CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); return this.getInquiryValueDao().getCount(trialId, active, activeSignup, probandId); } @Override protected long handleGetInquiryValueCount(AuthenticationVO auth, Long trialId, String category, Boolean active, Boolean activeSignup, Long probandId) throws Exception { Trial trial = CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); return this.getInquiryValueDao().getCount(trialId, category, active, activeSignup, probandId); } @Override protected InquiryValuesOutVO handleGetInquiryValues( AuthenticationVO auth, Long trialId, Boolean active, Boolean activeSignup, Long probandId, boolean sort, boolean loadAllJsValues, PSFVO psf) throws Exception { Trial trial = CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); ProbandDao probandDao = this.getProbandDao(); ProbandOutVO probandVO = probandDao.toProbandOutVO(CheckIDUtil.checkProbandId(probandId, probandDao)); return ServiceUtil.getInquiryValues(trial, probandVO, active, activeSignup, Settings.getBoolean(SettingCodes.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION, Bundle.SETTINGS, DefaultSettings.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION), loadAllJsValues, sort, psf, this.getInquiryDao(), this.getInquiryValueDao(), this.getInputFieldSelectionSetValueDao()); } @Override protected InquiryValuesOutVO handleGetInquiryValues( AuthenticationVO auth, Long trialId, String category, Boolean active, Boolean activeSignup, Long probandId, boolean sort, boolean loadAllJsValues, PSFVO psf) throws Exception { Trial trial = CheckIDUtil.checkTrialId(trialId, this.getTrialDao()); ProbandDao probandDao = this.getProbandDao(); ProbandOutVO probandVO = probandDao.toProbandOutVO(CheckIDUtil.checkProbandId(probandId, probandDao)); return getInquiryValues(trial, category, probandVO, active, activeSignup, Settings.getBoolean(SettingCodes.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION, Bundle.SETTINGS, DefaultSettings.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION), loadAllJsValues, sort, psf); } @Override protected MedicationOutVO handleGetMedication(AuthenticationVO auth, Long medicationId) throws Exception { MedicationDao medicationDao = this.getMedicationDao(); Medication medication = CheckIDUtil.checkMedicationId(medicationId, medicationDao); MedicationOutVO result = medicationDao.toMedicationOutVO(medication); return result; } @Override protected long handleGetMedicationCount(AuthenticationVO auth, Long probandId, Long diagnosisId, Long procedureId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } if (diagnosisId != null) { CheckIDUtil.checkDiagnosisId(diagnosisId, this.getDiagnosisDao()); } if (procedureId != null) { CheckIDUtil.checkProcedureId(procedureId, this.getProcedureDao()); } return this.getMedicationDao().getCount(probandId, diagnosisId, procedureId); } @Override protected Collection<MedicationOutVO> handleGetMedicationList(AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } MedicationDao medicationDao = this.getMedicationDao(); Collection medications = medicationDao.findByProband(probandId, psf); medicationDao.toMedicationOutVOCollection(medications); return medications; } @Override protected MoneyTransferOutVO handleGetMoneyTransfer(AuthenticationVO auth, Long moneyTransferId) throws Exception { MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); MoneyTransfer moneyTransfer = CheckIDUtil.checkMoneyTransferId(moneyTransferId, moneyTransferDao); MoneyTransferOutVO result = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); return result; } @Override protected long handleGetMoneyTransferCount(AuthenticationVO auth, Long probandId, Long bankAccountId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } if (bankAccountId != null) { CheckIDUtil.checkBankAccountId(bankAccountId, this.getBankAccountDao()); } return this.getMoneyTransferDao().getCount(null, probandId, bankAccountId, null, null, null); } @Override protected Collection<MoneyTransferOutVO> handleGetMoneyTransferList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); Collection moneyTransfers = moneyTransferDao.findByProbandTrialMethodCostTypePaidPerson(null, null, null, probandId, null, null, null, null, psf); moneyTransferDao.toMoneyTransferOutVOCollection(moneyTransfers); return moneyTransfers; } @Override protected String handleGetNewPaymentReference(AuthenticationVO auth, MoneyTransferInVO newMoneyTransfer) throws Exception { // TODO Auto-generated method stub return null; } @Override protected Collection<TrialOutVO> handleGetParticipationTrials(AuthenticationVO auth, Long probandId) throws Exception { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); TrialDao trialDao = this.getTrialDao(); Collection trials = trialDao.findByParticipatingProbandSorted(probandId); trialDao.toTrialOutVOCollection(trials); return trials; } /** * @see org.phoenixctms.ctsms.service.proband.ProbandService#getProband(Long) */ @Override protected ProbandOutVO handleGetProband(AuthenticationVO auth, Long probandId, Integer maxInstances, Integer maxParentsDepth, Integer maxChildrenDepth) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO result = probandDao.toProbandOutVO(proband, maxInstances, maxParentsDepth, maxChildrenDepth); return result; } @Override protected ProbandAddressOutVO handleGetProbandAddress(AuthenticationVO auth, Long probandAddressId) throws Exception { ProbandAddressDao addressDao = this.getProbandAddressDao(); ProbandAddress address = CheckIDUtil.checkProbandAddressId(probandAddressId, addressDao); ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address); return result; } @Override protected long handleGetProbandAddressCount( AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getProbandAddressDao().getCount(probandId, null, null, null); } @Override protected Collection<ProbandAddressOutVO> handleGetProbandAddressList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } ProbandAddressDao addressDao = this.getProbandAddressDao(); Collection probandAddresses = addressDao.findByProband(probandId, null, null, null, psf); addressDao.toProbandAddressOutVOCollection(probandAddresses); return probandAddresses; } @Override protected ProbandContactDetailValueOutVO handleGetProbandContactDetailValue( AuthenticationVO auth, Long probandContactDetailValueId) throws Exception { ProbandContactDetailValueDao contactValueDao = this.getProbandContactDetailValueDao(); ProbandContactDetailValue contactValue = CheckIDUtil.checkProbandContactDetailValueId(probandContactDetailValueId, contactValueDao); ProbandContactDetailValueOutVO result = contactValueDao.toProbandContactDetailValueOutVO(contactValue); return result; } @Override protected long handleGetProbandContactDetailValueCount( AuthenticationVO auth, Long probandId, Boolean na) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getProbandContactDetailValueDao().getCount(probandId, null, na, null, null); } @Override protected Collection<ProbandContactDetailValueOutVO> handleGetProbandContactDetailValueList( AuthenticationVO auth, Long probandId, Boolean na, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } ProbandContactDetailValueDao contactValueDao = this.getProbandContactDetailValueDao(); Collection probandContactValues = contactValueDao.findByProband(probandId, null, na, null, null, psf); contactValueDao.toProbandContactDetailValueOutVOCollection(probandContactValues); return probandContactValues; } @Override protected Collection<ProbandGroupOutVO> handleGetProbandGroupList( AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } ProbandGroupDao probandGroupDao = this.getProbandGroupDao(); Collection probandGroups = probandGroupDao.findByProbandSorted(probandId); probandGroupDao.toProbandGroupOutVOCollection(probandGroups); return probandGroups; } @Override protected ProbandImageOutVO handleGetProbandImage(AuthenticationVO auth, Long probandId) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandImageOutVO result = probandDao.toProbandImageOutVO(proband); return result; } @Override protected long handleGetProbandInventoryBookingCount( AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getInventoryBookingDao().getCount(null, probandId, null, null, null); } @Override protected Collection<InventoryBookingOutVO> handleGetProbandInventoryBookingList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } InventoryBookingDao inventoryBookingDao = this.getInventoryBookingDao(); Collection inventoryBookings = inventoryBookingDao.findByProband(probandId, psf); inventoryBookingDao.toInventoryBookingOutVOCollection(inventoryBookings); return inventoryBookings; } @Override protected Collection<ProbandOutVO> handleGetProbandList(AuthenticationVO auth, Long probandId, Long departmentId, Integer maxInstances, PSFVO psf) throws Exception { ProbandDao probandDao = this.getProbandDao(); if (probandId != null) { CheckIDUtil.checkProbandId(probandId, probandDao); } if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } Collection probands = probandDao.findByIdDepartment(probandId, departmentId, psf); ArrayList<ProbandOutVO> result = new ArrayList<ProbandOutVO>(probands.size()); Iterator<Proband> probandIt = probands.iterator(); while (probandIt.hasNext()) { result.add(probandDao.toProbandOutVO(probandIt.next(), maxInstances)); } return result; } @Override protected Collection<ProbandStatusEntryOutVO> handleGetProbandStatus( AuthenticationVO auth, Date now, Long probandId, Long departmentId, Long probandCategoryId, Boolean probandActive, Boolean hideAvailability, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } if (probandCategoryId != null) { CheckIDUtil.checkProbandCategoryId(probandCategoryId, this.getProbandCategoryDao()); } ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); Collection probandStatusEntries = statusEntryDao.findProbandStatus(CommonUtil.dateToTimestamp(now), probandId, departmentId, probandCategoryId, probandActive, hideAvailability, psf); statusEntryDao.toProbandStatusEntryOutVOCollection(probandStatusEntries); return probandStatusEntries; } @Override protected ProbandStatusEntryOutVO handleGetProbandStatusEntry( AuthenticationVO auth, Long probandStatusEntryId) throws Exception { ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); ProbandStatusEntry statusEntry = CheckIDUtil.checkProbandStatusEntryId(probandStatusEntryId, statusEntryDao); ProbandStatusEntryOutVO result = statusEntryDao.toProbandStatusEntryOutVO(statusEntry); return result; } @Override protected long handleGetProbandStatusEntryCount(AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getProbandStatusEntryDao().getCount(probandId); } @Override protected Collection<ProbandStatusEntryOutVO> handleGetProbandStatusEntryInterval(AuthenticationVO auth, Long departmentId, Long probandCategoryId, Boolean hideAvailability, Date from, Date to, boolean sort) throws Exception { if (departmentId != null) { CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } if (probandCategoryId != null) { CheckIDUtil.checkProbandCategoryId(probandCategoryId, this.getProbandCategoryDao()); } ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); Collection probandStatusEntries = statusEntryDao.findByDepartmentCategoryInterval(departmentId, probandCategoryId, CommonUtil.dateToTimestamp(from), CommonUtil.dateToTimestamp(to), null, null, hideAvailability); statusEntryDao.toProbandStatusEntryOutVOCollection(probandStatusEntries); if (sort) { probandStatusEntries = new ArrayList(probandStatusEntries); Collections.sort((ArrayList) probandStatusEntries, new ProbandStatusEntryIntervalComparator(false)); } return probandStatusEntries; } @Override protected Collection<ProbandStatusEntryOutVO> handleGetProbandStatusEntryList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); Collection probandStatusEntries = statusEntryDao.findByProband(probandId, psf); statusEntryDao.toProbandStatusEntryOutVOCollection(probandStatusEntries); return probandStatusEntries; } @Override protected ProbandTagValueOutVO handleGetProbandTagValue(AuthenticationVO auth, Long probandTagValueId) throws Exception { ProbandTagValueDao tagValueDao = this.getProbandTagValueDao(); ProbandTagValue tagValue = CheckIDUtil.checkProbandTagValueId(probandTagValueId, tagValueDao); ProbandTagValueOutVO result = tagValueDao.toProbandTagValueOutVO(tagValue); return result; } @Override protected long handleGetProbandTagValueCount(AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getProbandTagValueDao().getCount(probandId); } @Override protected Collection<ProbandTagValueOutVO> handleGetProbandTagValueList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } ProbandTagValueDao tagValueDao = this.getProbandTagValueDao(); Collection probandTagValues = tagValueDao.findByProband(probandId, psf); tagValueDao.toProbandTagValueOutVOCollection(probandTagValues); return probandTagValues; } @Override protected ProcedureOutVO handleGetProcedure(AuthenticationVO auth, Long procedureId) throws Exception { ProcedureDao procedureDao = this.getProcedureDao(); Procedure procedure = CheckIDUtil.checkProcedureId(procedureId, procedureDao); ProcedureOutVO result = procedureDao.toProcedureOutVO(procedure); return result; } @Override protected long handleGetProcedureCount( AuthenticationVO auth, Long probandId) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } return this.getProcedureDao().getCount(probandId); } @Override protected Collection<ProcedureOutVO> handleGetProcedureList( AuthenticationVO auth, Long probandId, PSFVO psf) throws Exception { if (probandId != null) { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); } ProcedureDao procedureDao = this.getProcedureDao(); Collection procedures = procedureDao.findByProband(probandId, psf); procedureDao.toProcedureOutVOCollection(procedures); return procedures; } @Override protected Collection<TrialOutVO> handleGetReimbursementTrials(AuthenticationVO auth, Long probandId, String costType, PaymentMethod method, Boolean paid) throws Exception { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); TrialDao trialDao = this.getTrialDao(); Collection trials = trialDao.findByReimbursementProbandSorted(probandId, method, costType, paid); trialDao.toTrialOutVOCollection(trials); return trials; } @Override protected ProbandAddressOutVO handleGetWireTransferProbandAddress(AuthenticationVO auth, Long probandId) throws Exception { CheckIDUtil.checkProbandId(probandId, this.getProbandDao()); ProbandAddressDao probandAddressDao = this.getProbandAddressDao(); return probandAddressDao.toProbandAddressOutVO(probandAddressDao.findByProbandWireTransfer(probandId)); } @Override protected InquiriesPDFVO handleRenderInquiries(AuthenticationVO auth, Long trialId, Long probandId, Boolean active, Boolean activeSignup, boolean blank) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO probandVO = probandDao.toProbandOutVO(proband); TrialDao trialDao = this.getTrialDao(); Trial trial = null; TrialOutVO trialVO = null; Collection<Trial> trials = new ArrayList<Trial>(); if (trialId != null) { trial = CheckIDUtil.checkTrialId(trialId, trialDao); trialVO = trialDao.toTrialOutVO(trial); trials.add(trial); } else { trials = trialDao.findByInquiryValuesProbandSorted(null, probandId, active, activeSignup); } InquiriesPDFVO result = ServiceUtil.renderInquiries(proband, probandVO, trials, active, activeSignup, blank, this.getTrialDao(), this.getInquiryDao(), this.getInquiryValueDao(), this.getInputFieldDao(), this.getInputFieldSelectionSetValueDao(), this.getUserDao()); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); if (trial != null) { ServiceUtil.logSystemMessage(trial, probandVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.INQUIRY_PDF_RENDERED, result, null, journalEntryDao); } ServiceUtil.logSystemMessage(proband, trialVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), trial != null ? SystemMessageCodes.INQUIRY_PDF_RENDERED : SystemMessageCodes.INQUIRIES_PDF_RENDERED, result, null, journalEntryDao); return result; } @Override protected InquiriesPDFVO handleRenderInquiriesSignup(AuthenticationVO auth, Long departmentId, Long probandId, Boolean activeSignup) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO probandVO = probandDao.toProbandOutVO(proband); Department department = null; if (departmentId != null) { department = CheckIDUtil.checkDepartmentId(departmentId, this.getDepartmentDao()); } Collection<Trial> trials = new ArrayList<Trial>(); Iterator<Trial> trialIt = this.getTrialDao().findBySignup(department != null ? department.getId() : null, true, null).iterator(); while (trialIt.hasNext()) { Trial trial = trialIt.next(); if (this.getInquiryValueDao().getCount(trial.getId(), null, activeSignup, proband.getId()) > 0) { trials.add(trial); } } InquiriesPDFVO result = ServiceUtil.renderInquiries(proband, probandVO, trials, null, activeSignup, false, this.getTrialDao(), this.getInquiryDao(), this.getInquiryValueDao(), this.getInputFieldDao(), this.getInputFieldSelectionSetValueDao(), this.getUserDao()); ServiceUtil.logSystemMessage(proband, (TrialOutVO) null, CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.INQUIRIES_SIGNUP_PDF_RENDERED, result, null, this.getJournalEntryDao()); return result; } @Override protected InquiriesPDFVO handleRenderInquiry(AuthenticationVO auth, Long trialId, String category, Long probandId, Boolean active, Boolean activeSignup, boolean blank) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO probandVO = probandDao.toProbandOutVO(proband); TrialDao trialDao = this.getTrialDao(); Trial trial = CheckIDUtil.checkTrialId(trialId, trialDao); TrialOutVO trialVO = trialDao.toTrialOutVO(trial); Collection<Trial> trials = new ArrayList<Trial>(); trials.add(trial); InquiriesPDFVO result = ServiceUtil.renderInquiries(proband, probandVO, trials, active, activeSignup, blank, this.getTrialDao(), this.getInquiryDao(), this.getInquiryValueDao(), this.getInputFieldDao(), this.getInputFieldSelectionSetValueDao(), this.getUserDao()); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); ServiceUtil.logSystemMessage(trial, probandVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.INQUIRY_PDF_RENDERED, result, null, journalEntryDao); ServiceUtil.logSystemMessage(proband, trialVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), CoreUtil.getUser(), SystemMessageCodes.INQUIRY_PDF_RENDERED, result, null, journalEntryDao); return result; } @Override protected ProbandLetterPDFVO handleRenderProbandLetterPDF( AuthenticationVO auth, Long probandAddressId) throws Exception { ProbandAddressDao probandAddressDao = this.getProbandAddressDao(); ProbandAddress address = CheckIDUtil.checkProbandAddressId(probandAddressId, probandAddressDao); if (!address.getProband().isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_LETTER_NOT_FOR_ANIMAL_ENTRIES); } ProbandAddressOutVO addressVO = probandAddressDao.toProbandAddressOutVO(address); ProbandLetterPDFPainter painter = ServiceUtil.createProbandLetterPDFPainter(addressVO); User user = CoreUtil.getUser(); painter.getPdfVO().setRequestingUser(this.getUserDao().toUserOutVO(user)); (new PDFImprinter(painter, painter)).render(); ProbandLetterPDFVO result = painter.getPdfVO(); logSystemMessage(address.getProband(), addressVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), user, SystemMessageCodes.PROBAND_ADDRESS_PROBAND_LETTER_PDF_RENDERED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandLetterPDFVO handleRenderProbandLettersPDF( AuthenticationVO auth, Long probandId) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); if (!proband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_LETTER_NOT_FOR_ANIMAL_ENTRIES); } ArrayList<ProbandOutVO> probandVOs = new ArrayList<ProbandOutVO>(); ProbandOutVO probandVO = probandDao.toProbandOutVO(proband); probandVOs.add(probandVO); ProbandLetterPDFPainter painter = ServiceUtil.createProbandLetterPDFPainter(probandVOs, this.getProbandAddressDao()); User user = CoreUtil.getUser(); painter.getPdfVO().setRequestingUser(this.getUserDao().toUserOutVO(user)); (new PDFImprinter(painter, painter)).render(); ProbandLetterPDFVO result = painter.getPdfVO(); ServiceUtil.logSystemMessage(proband, probandVO, CommonUtil.dateToTimestamp(result.getContentTimestamp()), user, SystemMessageCodes.PROBAND_LETTER_PDF_RENDERED, result, null, this.getJournalEntryDao()); return result; } @Override protected ProbandOutVO handleResetAutoDeleteDeadline( AuthenticationVO auth, Long probandId, Long version) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO original = probandDao.toProbandOutVO(proband); ServiceUtil.checkProbandLocked(proband); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(proband, version.longValue(), now, user); ServiceUtil.resetAutoDeleteDeadline(proband, now); probandDao.update(proband); ServiceUtil.notifyExpiringProbandAutoDelete(proband, now, this.getNotificationDao()); ProbandOutVO result = probandDao.toProbandOutVO(proband); ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PROBAND_AUTO_DELETE_DEADLINE_RESET, result, original, this.getJournalEntryDao()); return result; } @Override protected Collection<MoneyTransferOutVO> handleSetAllMoneyTransfersPaid( AuthenticationVO auth, Long probandId, Long trialId, boolean paid) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao, LockMode.PESSIMISTIC_WRITE); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } if (!proband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PROBAND_NOT_PERSON); } ServiceUtil.checkProbandLocked(proband); TrialDao trialDao = this.getTrialDao(); Trial trial = null; if (trialId != null) { trial = CheckIDUtil.checkTrialId(trialId, trialDao); } JournalEntryDao journalEntryDao = this.getJournalEntryDao(); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); Collection<MoneyTransfer> moneyTransfers = moneyTransferDao.findByProbandTrialMethodCostTypePaidPerson(null, trial == null ? null : trial.getId(), null, proband.getId(), null, null, !paid, null, null); if (moneyTransfers.size() == 0) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PAID_NOT_CHANGED); } ArrayList<MoneyTransferOutVO> results = new ArrayList<MoneyTransferOutVO>(moneyTransfers.size()); Iterator<MoneyTransfer> moneyTransfersIt = moneyTransfers.iterator(); while (moneyTransfersIt.hasNext()) { MoneyTransfer moneyTransfer = moneyTransfersIt.next(); MoneyTransferOutVO original = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_MONEY_TRANSFER); } Trial moneyTransferTrial = moneyTransfer.getTrial(); if (moneyTransferTrial != null) { ServiceUtil.checkTrialLocked(moneyTransferTrial); } moneyTransfer.setPaid(paid); CoreUtil.modifyVersion(moneyTransfer, moneyTransfer, now, user); moneyTransferDao.update(moneyTransfer); MoneyTransferOutVO result = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); if (moneyTransferTrial != null) { logSystemMessage(moneyTransferTrial, result.getProband(), now, user, paid ? SystemMessageCodes.MONEY_TRANSFER_PAID_SET : SystemMessageCodes.MONEY_TRANSFER_PAID_UNSET, result, original, journalEntryDao); } ServiceUtil.logSystemMessage(moneyTransfer.getProband(), original.getProband(), now, user, paid ? SystemMessageCodes.MONEY_TRANSFER_PAID_SET : SystemMessageCodes.MONEY_TRANSFER_PAID_UNSET, result, original, journalEntryDao); results.add(result); } return results; } @Override protected InquiryValuesOutVO handleSetInquiryValues( AuthenticationVO auth, Set<InquiryValueInVO> inquiryValuesIn, boolean force) throws Exception { Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); InquiryValuesOutVO result = new InquiryValuesOutVO(); ServiceException firstException = null; HashMap<Long, String> errorMessagesMap = new HashMap<Long, String>(); Proband proband = null; if (inquiryValuesIn != null && inquiryValuesIn.size() > 0) { Trial trial = null; ArrayList<InquiryValueOutVO> inquiryValues = new ArrayList<InquiryValueOutVO>(inquiryValuesIn.size()); ArrayList<InquiryValueJsonVO> jsInquiryValues = null; if (Settings.getBoolean(SettingCodes.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION, Bundle.SETTINGS, DefaultSettings.INQUIRY_VALUES_ENABLE_BROWSER_FIELD_CALCULATION)) { jsInquiryValues = new ArrayList<InquiryValueJsonVO>(inquiryValuesIn.size()); } Iterator<InquiryValueInVO> inquiryValuesInIt = inquiryValuesIn.iterator(); while (inquiryValuesInIt.hasNext()) { InquiryValueInVO inquiryValueIn = inquiryValuesInIt.next(); Inquiry inquiry = CheckIDUtil.checkInquiryId(inquiryValueIn.getInquiryId(), this.getInquiryDao()); if (trial == null) { trial = inquiry.getTrial(); ServiceUtil.checkTrialLocked(trial); if (!trial.getStatus().isInquiryValueInputEnabled()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INQUIRY_VALUE_INPUT_DISABLED_FOR_TRIAL, CommonUtil.trialOutVOToString(this.getTrialDao().toTrialOutVO(trial))); } } else if (!trial.equals(inquiry.getTrial())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INQUIRY_VALUES_FOR_DIFFERENT_TRIALS); } if (proband == null) { proband = CheckIDUtil.checkProbandId(inquiryValueIn.getProbandId(), this.getProbandDao(), LockMode.PESSIMISTIC_WRITE); ServiceUtil.checkProbandLocked(proband); } else if (!proband.getId().equals(inquiryValueIn.getProbandId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INQUIRY_VALUES_FOR_DIFFERENT_PROBANDS); } try { addUpdateInquiryValue(inquiryValueIn, proband, inquiry, now, user, force, Settings.getBoolean(SettingCodes.LOG_INQUIRY_VALUE_TRIAL, Bundle.SETTINGS, DefaultSettings.LOG_INQUIRY_VALUE_TRIAL), Settings.getBoolean(SettingCodes.LOG_INQUIRY_VALUE_PROBAND, Bundle.SETTINGS, DefaultSettings.LOG_INQUIRY_VALUE_PROBAND), inquiryValues, jsInquiryValues); } catch (ServiceException e) { if (firstException == null) { firstException = e; } errorMessagesMap.put(inquiry.getId(), e.getMessage()); } } if (firstException != null) { firstException.setData(errorMessagesMap); throw firstException; } Collections.sort(inquiryValues, new InquiryValueOutVOComparator()); result.setPageValues(inquiryValues); if (jsInquiryValues != null) { result.setJsValues(jsInquiryValues); } } return result; } @Override protected MoneyTransferOutVO handleSetMoneyTransferPaid( AuthenticationVO auth, Long moneyTransferId, Long version, boolean paid) throws Exception { MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); MoneyTransfer moneyTransfer = CheckIDUtil.checkMoneyTransferId(moneyTransferId, moneyTransferDao); MoneyTransferOutVO original = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_MONEY_TRANSFER); } ProbandDao probandDao = this.getProbandDao(); Proband proband = moneyTransfer.getProband(); if (!proband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PROBAND_NOT_PERSON); } probandDao.lock(proband, LockMode.PESSIMISTIC_WRITE); if (!probandDao.toProbandOutVO(proband).isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ServiceUtil.checkProbandLocked(proband); Trial trial = moneyTransfer.getTrial(); if (trial != null) { ServiceUtil.checkTrialLocked(trial); } if (paid == original.getPaid()) { // unboxed, ok throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PAID_NOT_CHANGED); } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(moneyTransfer, version.longValue(), now, user); moneyTransfer.setPaid(paid); moneyTransferDao.update(moneyTransfer); MoneyTransferOutVO result = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); if (trial != null) { logSystemMessage(trial, result.getProband(), now, user, paid ? SystemMessageCodes.MONEY_TRANSFER_PAID_SET : SystemMessageCodes.MONEY_TRANSFER_PAID_UNSET, result, original, journalEntryDao); } ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, paid ? SystemMessageCodes.MONEY_TRANSFER_PAID_SET : SystemMessageCodes.MONEY_TRANSFER_PAID_UNSET, result, original, journalEntryDao); return result; } @Override protected ProbandAddressOutVO handleSetProbandAddressWireTransfer( AuthenticationVO auth, Long probandAddressId, Long version) throws Exception { ProbandAddressDao addressDao = this.getProbandAddressDao(); ProbandAddress address = CheckIDUtil.checkProbandAddressId(probandAddressId, addressDao); Proband proband = address.getProband(); this.getProbandDao().lock(proband, LockMode.PESSIMISTIC_WRITE); ProbandAddressOutVO original = addressDao.toProbandAddressOutVO(address); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_ADDRESS); } ServiceUtil.checkProbandLocked(proband); if (address.isWireTransfer()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_ADDRESS_WIRE_TRANSFER_NOT_CHANGED); } JournalEntryDao journalEntryDao = this.getJournalEntryDao(); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); Iterator<ProbandAddress> addressesIt = addressDao.findByProband(proband.getId(), null, null, true, null).iterator(); while (addressesIt.hasNext()) { ProbandAddress oldWireTransferAddress = addressesIt.next(); ProbandAddressOutVO oldWireTransferAddressOriginal = addressDao.toProbandAddressOutVO(address); oldWireTransferAddress.setWireTransfer(false); CoreUtil.modifyVersion(oldWireTransferAddress, oldWireTransferAddress, now, user); addressDao.update(oldWireTransferAddress); ProbandAddressOutVO oldWireTransferAddressResult = addressDao.toProbandAddressOutVO(address); ServiceUtil.logSystemMessage(oldWireTransferAddress.getProband(), oldWireTransferAddressOriginal.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_WIRE_TRANSFER_UNSET, oldWireTransferAddressResult, oldWireTransferAddressOriginal, journalEntryDao); } address.setWireTransfer(true); CoreUtil.modifyVersion(address, version.longValue(), now, user); addressDao.update(address); ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address); ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_WIRE_TRANSFER_SET, result, original, journalEntryDao); return result; } @Override protected ProbandImageOutVO handleSetProbandImage(AuthenticationVO auth, ProbandImageInVO probandImage) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband originalProband = CheckIDUtil.checkProbandId(probandImage.getId(), probandDao); ProbandImageOutVO original = probandDao.toProbandImageOutVO(originalProband); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ServiceUtil.checkProbandLocked(originalProband); checkProbandImageInput(probandImage); boolean hasImage = original.getHasImage(); boolean cleared = probandImage.getDatas() == null || probandImage.getDatas().length == 0; probandDao.evict(originalProband); Proband proband = probandDao.probandImageInVOToEntity(probandImage); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalProband, proband, now, user); probandDao.update(proband); ProbandImageOutVO result = probandDao.toProbandImageOutVO(proband); ServiceUtil.logSystemMessage(proband, probandDao.toProbandOutVO(proband), now, user, cleared ? SystemMessageCodes.PROBAND_IMAGE_CLEARED : hasImage ? SystemMessageCodes.PROBAND_IMAGE_UPDATED : SystemMessageCodes.PROBAND_IMAGE_CREATED, result, original, this.getJournalEntryDao()); return result; } @Override protected BankAccountOutVO handleUpdateBankAccount( AuthenticationVO auth, BankAccountInVO modifiedBankAccount) throws Exception { BankAccountDao bankAccountDao = this.getBankAccountDao(); BankAccount originalBankAccount = CheckIDUtil.checkBankAccountId(modifiedBankAccount.getId(), bankAccountDao); BankAccountOutVO original = bankAccountDao.toBankAccountOutVO(originalBankAccount); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_BANK_ACCOUNT); } checkBankAccountInput(modifiedBankAccount); if (!modifiedBankAccount.getProbandId().equals(originalBankAccount.getProband().getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.BANK_ACCOUNT_PROBAND_CHANGED); } bankAccountDao.evict(originalBankAccount); BankAccount bankAccount = bankAccountDao.bankAccountInVOToEntity(modifiedBankAccount); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalBankAccount, bankAccount, now, user); bankAccountDao.update(bankAccount); BankAccountOutVO result = bankAccountDao.toBankAccountOutVO(bankAccount); ServiceUtil .logSystemMessage(bankAccount.getProband(), result.getProband(), now, user, SystemMessageCodes.BANK_ACCOUNT_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected DiagnosisOutVO handleUpdateDiagnosis(AuthenticationVO auth, DiagnosisInVO modifiedDiagnosis) throws Exception { DiagnosisDao diagnosisDao = this.getDiagnosisDao(); Diagnosis originalDiagnosis = CheckIDUtil.checkDiagnosisId(modifiedDiagnosis.getId(), diagnosisDao); DiagnosisOutVO original = diagnosisDao.toDiagnosisOutVO(originalDiagnosis); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_DIAGNOSIS); } checkDiagnosisInput(modifiedDiagnosis); diagnosisDao.evict(originalDiagnosis); Diagnosis diagnosis = diagnosisDao.diagnosisInVOToEntity(modifiedDiagnosis); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalDiagnosis, diagnosis, now, user); diagnosisDao.update(diagnosis); DiagnosisOutVO result = diagnosisDao.toDiagnosisOutVO(diagnosis); ServiceUtil.logSystemMessage(diagnosis.getProband(), result.getProband(), now, user, SystemMessageCodes.DIAGNOSIS_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected MedicationOutVO handleUpdateMedication(AuthenticationVO auth, MedicationInVO modifiedMedication) throws Exception { MedicationDao medicationDao = this.getMedicationDao(); Medication originalMedication = CheckIDUtil.checkMedicationId(modifiedMedication.getId(), medicationDao); MedicationOutVO original = medicationDao.toMedicationOutVO(originalMedication); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_MEDICATION); } checkMedicationInput(modifiedMedication); if (!modifiedMedication.getProbandId().equals(originalMedication.getProband().getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MEDICATION_PROBAND_CHANGED); } medicationDao.evict(originalMedication); Medication medication = medicationDao.medicationInVOToEntity(modifiedMedication); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalMedication, medication, now, user); medicationDao.update(medication); MedicationOutVO result = medicationDao.toMedicationOutVO(medication); ServiceUtil.logSystemMessage(medication.getProband(), result.getProband(), now, user, SystemMessageCodes.MEDICATION_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected MoneyTransferOutVO handleUpdateMoneyTransfer( AuthenticationVO auth, MoneyTransferInVO modifiedMoneyTransfer, Long maxAllowedCostTypes) throws Exception { MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); MoneyTransfer originalMoneyTransfer = CheckIDUtil.checkMoneyTransferId(modifiedMoneyTransfer.getId(), moneyTransferDao); MoneyTransferOutVO original = moneyTransferDao.toMoneyTransferOutVO(originalMoneyTransfer); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_MONEY_TRANSFER); } checkMoneyTransferInput(modifiedMoneyTransfer, maxAllowedCostTypes); if (!modifiedMoneyTransfer.getProbandId().equals(originalMoneyTransfer.getProband().getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.MONEY_TRANSFER_PROBAND_CHANGED); } moneyTransferDao.evict(originalMoneyTransfer); MoneyTransfer moneyTransfer = moneyTransferDao.moneyTransferInVOToEntity(modifiedMoneyTransfer); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalMoneyTransfer, moneyTransfer, now, user); moneyTransferDao.update(moneyTransfer); Trial trial = moneyTransfer.getTrial(); MoneyTransferOutVO result = moneyTransferDao.toMoneyTransferOutVO(moneyTransfer); if (trial != null) { logSystemMessage(trial, result.getProband(), now, user, SystemMessageCodes.MONEY_TRANSFER_UPDATED, result, original, this.getJournalEntryDao()); } ServiceUtil.logSystemMessage(moneyTransfer.getProband(), result.getProband(), now, user, SystemMessageCodes.MONEY_TRANSFER_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected ProbandOutVO handleUpdatePrivacyConsentStatus( AuthenticationVO auth, Long probandId, Long version, Long privacyConsentStatusTypeId) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO original = probandDao.toProbandOutVO(proband); PrivacyConsentStatusTypeDao privacyConsentStatusTypeDao = this.getPrivacyConsentStatusTypeDao(); PrivacyConsentStatusType state = CheckIDUtil.checkPrivacyConsentStatusTypeId(privacyConsentStatusTypeId, privacyConsentStatusTypeDao); ServiceUtil.checkProbandLocked(proband); boolean validState = false; Iterator<PrivacyConsentStatusType> statesIt = privacyConsentStatusTypeDao.findTransitions(proband.getPrivacyConsentStatus().getId()).iterator(); while (statesIt.hasNext()) { if (state.equals(statesIt.next())) { validState = true; break; } } if (!validState) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_NEW_PRIVACY_CONSENT_STATUS_TYPE, L10nUtil.getPrivacyConsentStatusTypeName(Locales.USER, state.getNameL10nKey())); } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(proband, version.longValue(), now, user); proband.setPrivacyConsentStatus(state); probandDao.update(proband); ServiceUtil.notifyExpiringProbandAutoDelete(proband, now, this.getNotificationDao()); ProbandOutVO result = probandDao.toProbandOutVO(proband); ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PRIVACY_CONSENT_STATUS_TYPE_UPDATED, result, original, this.getJournalEntryDao()); return probandDao.toProbandOutVO(proband); } @Override protected ProbandOutVO handleUpdateProband(AuthenticationVO auth, ProbandInVO modifiedProband, Integer maxInstances, Integer maxParentsDepth, Integer maxChildrenDepth) throws Exception { ProbandDao probandDao = this.getProbandDao(); User user = CoreUtil.getUser(); this.getUserDao().lock(user, LockMode.PESSIMISTIC_WRITE); Proband originalProband = CheckIDUtil.checkProbandId(modifiedProband.getId(), probandDao, LockMode.PESSIMISTIC_WRITE); ProbandOutVO original = probandDao.toProbandOutVO(originalProband, maxInstances, maxParentsDepth, maxChildrenDepth); if (modifiedProband.getBlinded()) { if (!user.getDepartment().getId().equals(modifiedProband.getDepartmentId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DEPARTMENT_NOT_EQUAL_TO_USER_DEPARTMENT); } if (!modifiedProband.getDepartmentId().equals(originalProband.getDepartment().getId())) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DEPARTMENT_CHANGED); } } else { if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } } checkProbandInput(modifiedProband); if (originalProband.isPerson() != modifiedProband.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_PERSON_FLAG_CHANGED); } boolean originalPrivacyConsentControl = originalProband.getCategory().isPrivacyConsentControl(); probandDao.evict(originalProband); Proband proband = probandDao.probandInVOToEntity(modifiedProband); checkProbandLoop(proband); Timestamp now = new Timestamp(System.currentTimeMillis()); CoreUtil.modifyVersion(originalProband, proband, now, user); if (!originalPrivacyConsentControl && proband.getCategory().isPrivacyConsentControl()) { ServiceUtil.resetAutoDeleteDeadline(proband, now); proband.setPrivacyConsentStatus(this.getPrivacyConsentStatusTypeDao().findInitialStates().iterator().next()); } probandDao.update(proband); ServiceUtil.notifyExpiringProbandAutoDelete(proband, now, this.getNotificationDao()); ProbandOutVO result = probandDao.toProbandOutVO(proband, maxInstances, maxParentsDepth, maxChildrenDepth); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PROBAND_UPDATED, result, original, journalEntryDao); Staff physician = proband.getPhysician(); if (physician != null) { ServiceUtil.logSystemMessage(physician, result, now, user, SystemMessageCodes.PROBAND_UPDATED, result, original, journalEntryDao); } Iterator<ProbandOutVO> parentsIt = original.getParents().iterator(); while (parentsIt.hasNext()) { ProbandOutVO parent = parentsIt.next(); ServiceUtil.logSystemMessage(probandDao.load(parent.getId()), result, now, user, SystemMessageCodes.PROBAND_UPDATED, result, original, journalEntryDao); } return result; } @Override protected ProbandAddressOutVO handleUpdateProbandAddress( AuthenticationVO auth, ProbandAddressInVO modifiedProbandAddress) throws Exception { ProbandAddressDao addressDao = this.getProbandAddressDao(); ProbandAddress originalAddress = CheckIDUtil.checkProbandAddressId(modifiedProbandAddress.getId(), addressDao); ProbandAddressOutVO original = addressDao.toProbandAddressOutVO(originalAddress); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_ADDRESS); } checkProbandAddressInput(modifiedProbandAddress); addressDao.evict(originalAddress); ProbandAddress address = addressDao.probandAddressInVOToEntity(modifiedProbandAddress); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalAddress, address, now, user); addressDao.update(address); ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address); ServiceUtil.logSystemMessage(address.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected ProbandOutVO handleUpdateProbandCategory( AuthenticationVO auth, Long probandId, Long version, Long categoryId, String comment) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao); ProbandOutVO original = probandDao.toProbandOutVO(proband); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND); } ProbandCategory category = CheckIDUtil.checkProbandCategoryId(categoryId, this.getProbandCategoryDao()); if (proband.isPerson()) { if (!category.isPerson()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CATEGORY_NOT_FOR_PERSON_ENTRIES, L10nUtil.getProbandCategoryName(Locales.USER, category.getNameL10nKey())); } } else { if (!category.isAnimal()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_CATEGORY_NOT_FOR_ANIMAL_ENTRIES, L10nUtil.getProbandCategoryName(Locales.USER, category.getNameL10nKey())); } } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(proband, version.longValue(), now, user); proband.setCategory(category); if (proband.isPerson()) { ProbandContactParticulars personParticulars = proband.getPersonParticulars(); if (personParticulars != null) { CipherText cipherText = CryptoUtil.encryptValue(comment); personParticulars.setCommentIv(cipherText.getIv()); personParticulars.setEncryptedComment(cipherText.getCipherText()); personParticulars.setCommentHash(CryptoUtil.hashForSearch(comment)); } } else { AnimalContactParticulars animalParticulars = proband.getAnimalParticulars(); if (animalParticulars != null) { animalParticulars.setComment(comment); } } probandDao.update(proband); ProbandOutVO result = probandDao.toProbandOutVO(proband); ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PROBAND_CATEGORY_UPDATED, result, original, this.getJournalEntryDao()); return probandDao.toProbandOutVO(proband); } @Override protected ProbandContactDetailValueOutVO handleUpdateProbandContactDetailValue( AuthenticationVO auth, ProbandContactDetailValueInVO modifiedProbandContactDetailValue) throws Exception { ProbandContactDetailValueDao contactValueDao = this.getProbandContactDetailValueDao(); ProbandContactDetailValue originalContactValue = CheckIDUtil.checkProbandContactDetailValueId(modifiedProbandContactDetailValue.getId(), contactValueDao); ProbandContactDetailValueOutVO original = contactValueDao.toProbandContactDetailValueOutVO(originalContactValue); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_CONTACT_DETAIL_VALUE); } checkProbandContactDetailValueInput(modifiedProbandContactDetailValue); contactValueDao.evict(originalContactValue); ProbandContactDetailValue contactValue = contactValueDao.probandContactDetailValueInVOToEntity(modifiedProbandContactDetailValue); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalContactValue, contactValue, now, user); contactValueDao.update(contactValue); ProbandContactDetailValueOutVO result = contactValueDao.toProbandContactDetailValueOutVO(contactValue); ServiceUtil.logSystemMessage(contactValue.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_CONTACT_DETAIL_VALUE_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected ProbandStatusEntryOutVO handleUpdateProbandStatusEntry( AuthenticationVO auth, ProbandStatusEntryInVO modifiedProbandStatusEntry) throws Exception { ProbandStatusEntryDao statusEntryDao = this.getProbandStatusEntryDao(); ProbandStatusEntry originalStatusEntry = CheckIDUtil.checkProbandStatusEntryId(modifiedProbandStatusEntry.getId(), statusEntryDao); ProbandStatusEntryOutVO original = statusEntryDao.toProbandStatusEntryOutVO(originalStatusEntry); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_STATUS_ENTRY); } checkProbandStatusEntryInput(modifiedProbandStatusEntry); statusEntryDao.evict(originalStatusEntry); ProbandStatusEntry statusEntry = statusEntryDao.probandStatusEntryInVOToEntity(modifiedProbandStatusEntry); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalStatusEntry, statusEntry, now, user); statusEntryDao.update(statusEntry); notifyProbandInactive(statusEntry, now); ProbandStatusEntryOutVO result = statusEntryDao.toProbandStatusEntryOutVO(statusEntry); ServiceUtil.logSystemMessage(statusEntry.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_STATUS_ENTRY_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected ProbandTagValueOutVO handleUpdateProbandTagValue( AuthenticationVO auth, ProbandTagValueInVO modifiedProbandTagValue) throws Exception { ProbandTagValueDao tagValueDao = this.getProbandTagValueDao(); ProbandTagValue originalTagValue = CheckIDUtil.checkProbandTagValueId(modifiedProbandTagValue.getId(), tagValueDao); ProbandTagValueOutVO original = tagValueDao.toProbandTagValueOutVO(originalTagValue); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_TAG_VALUE); } checkProbandTagValueInput(modifiedProbandTagValue); tagValueDao.evict(originalTagValue); ProbandTagValue tagValue = tagValueDao.probandTagValueInVOToEntity(modifiedProbandTagValue); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalTagValue, tagValue, now, user); tagValueDao.update(tagValue); ProbandTagValueOutVO result = tagValueDao.toProbandTagValueOutVO(tagValue); ServiceUtil.logSystemMessage(tagValue.getProband(), result.getProband(), now, user, SystemMessageCodes.PROBAND_TAG_VALUE_UPDATED, result, original, this.getJournalEntryDao()); return result; } @Override protected ProcedureOutVO handleUpdateProcedure(AuthenticationVO auth, ProcedureInVO modifiedProcedure) throws Exception { ProcedureDao procedureDao = this.getProcedureDao(); Procedure originalProcedure = CheckIDUtil.checkProcedureId(modifiedProcedure.getId(), procedureDao); ProcedureOutVO original = procedureDao.toProcedureOutVO(originalProcedure); if (!original.isDecrypted()) { throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROCEDURE); } checkProcedureInput(modifiedProcedure); procedureDao.evict(originalProcedure); Procedure procedure = procedureDao.procedureInVOToEntity(modifiedProcedure); Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); CoreUtil.modifyVersion(originalProcedure, procedure, now, user); procedureDao.update(procedure); ProcedureOutVO result = procedureDao.toProcedureOutVO(procedure); ServiceUtil.logSystemMessage(procedure.getProband(), result.getProband(), now, user, SystemMessageCodes.PROCEDURE_UPDATED, result, original, this.getJournalEntryDao()); return result; } private void notifyProbandInactive(ProbandStatusEntry statusEntry, Date now) throws Exception { NotificationDao notificationDao = this.getNotificationDao(); ServiceUtil.cancelNotifications(statusEntry.getNotifications(), notificationDao, null); // clears inventory_active AND inventory inactive booking notifications if (!statusEntry.getType().isProbandActive()) { if ((new DateInterval(statusEntry.getStart(), statusEntry.getStop())).contains(now)) { notificationDao.addNotification(statusEntry, now, null); } if (!(new DateInterval(statusEntry.getStart(), statusEntry.getStop())).isOver(now)) { VisitScheduleItemDao visitScheduleItemDao = this.getVisitScheduleItemDao(); Proband proband = statusEntry.getProband(); Iterator<ProbandListEntry> trialParticipationsIt = proband.getTrialParticipations().iterator(); while (trialParticipationsIt.hasNext()) { ProbandListEntry probandListEntry = trialParticipationsIt.next(); ProbandGroup probandGroup = probandListEntry.getGroup(); if (probandGroup != null) { Iterator<VisitScheduleItem> it = visitScheduleItemDao .findByInterval(probandListEntry.getTrial().getId(), probandGroup.getId(), proband.getId(), statusEntry.getStart(), statusEntry.getStop()) .iterator(); while (it.hasNext()) { notificationDao.addNotification(it.next(), proband, statusEntry, now, null); } } } } } } @Override protected ProbandOutVO handleUpdateProbandDepartment(AuthenticationVO auth, Long probandId, Long newDepartmentId, String plainNewDepartmentPassword, String plainOldDepartmentPassword) throws Exception { ProbandDao probandDao = this.getProbandDao(); Proband proband = CheckIDUtil.checkProbandId(probandId, probandDao, LockMode.PESSIMISTIC_WRITE); Department newDepartment = CheckIDUtil.checkDepartmentId(newDepartmentId, this.getDepartmentDao()); if (plainNewDepartmentPassword == null) { plainNewDepartmentPassword = CoreUtil.getUserContext().getPlainDepartmentPassword(); } if (plainOldDepartmentPassword == null) { plainOldDepartmentPassword = CoreUtil.getUserContext().getPlainDepartmentPassword(); } Department oldDepartment = proband.getDepartment(); if (!oldDepartment.equals(newDepartment)) { if (!CryptoUtil.checkDepartmentPassword(newDepartment, plainNewDepartmentPassword)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.DEPARTMENT_PASSWORD_WRONG); } if (!CryptoUtil.checkDepartmentPassword(oldDepartment, plainOldDepartmentPassword)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.OLD_DEPARTMENT_PASSWORD_WRONG); } Timestamp now = new Timestamp(System.currentTimeMillis()); User user = CoreUtil.getUser(); SecretKey newDepartmentKey = ReEncrypter.getDepartmenKey(newDepartment, plainNewDepartmentPassword); SecretKey oldDepartmentKey = ReEncrypter.getDepartmenKey(oldDepartment, plainOldDepartmentPassword); ProbandOutVO original = probandDao.toProbandOutVO(proband); probandDao.reEncrypt(proband, oldDepartmentKey, newDepartmentKey); proband.setDepartment(newDepartment); CoreUtil.modifyVersion(proband, proband.getVersion(), now, user); probandDao.update(proband); ProbandOutVO result = probandDao.toProbandOutVO(proband); ProbandTagValueDao probandTagValueDao = this.getProbandTagValueDao(); Iterator<ProbandTagValue> tagValuesIt = proband.getTagValues().iterator(); while (tagValuesIt.hasNext()) { ProbandTagValue tagValue = tagValuesIt.next(); probandTagValueDao.reEncrypt(tagValue, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(tagValue, tagValue.getVersion(), now, user); probandTagValueDao.update(tagValue); } ProbandContactDetailValueDao probandContactDetailValueDao = this.getProbandContactDetailValueDao(); Iterator<ProbandContactDetailValue> contactDetailValuesIt = proband.getContactDetailValues().iterator(); while (contactDetailValuesIt.hasNext()) { ProbandContactDetailValue contactDetailValue = contactDetailValuesIt.next(); probandContactDetailValueDao.reEncrypt(contactDetailValue, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(contactDetailValue, contactDetailValue.getVersion(), now, user); probandContactDetailValueDao.update(contactDetailValue); } ProbandAddressDao probandAddressDao = this.getProbandAddressDao(); Iterator<ProbandAddress> addressesIt = proband.getAddresses().iterator(); while (addressesIt.hasNext()) { ProbandAddress address = addressesIt.next(); probandAddressDao.reEncrypt(address, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(address, address.getVersion(), now, user); probandAddressDao.update(address); } ProbandStatusEntryDao probandStatusEntryDao = this.getProbandStatusEntryDao(); Iterator<ProbandStatusEntry> statusEntriesIt = proband.getStatusEntries().iterator(); while (statusEntriesIt.hasNext()) { ProbandStatusEntry statusEntry = statusEntriesIt.next(); probandStatusEntryDao.reEncrypt(statusEntry, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(statusEntry, statusEntry.getVersion(), now, user); probandStatusEntryDao.update(statusEntry); } MedicationDao medicationDao = this.getMedicationDao(); Iterator<Medication> medicationsIt = proband.getMedications().iterator(); while (medicationsIt.hasNext()) { Medication medication = medicationsIt.next(); medicationDao.reEncrypt(medication, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(medication, medication.getVersion(), now, user); medicationDao.update(medication); } DiagnosisDao diagnosisDao = this.getDiagnosisDao(); Iterator<Diagnosis> diagnosesIt = proband.getDiagnoses().iterator(); while (diagnosesIt.hasNext()) { Diagnosis diagnosis = diagnosesIt.next(); diagnosisDao.reEncrypt(diagnosis, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(diagnosis, diagnosis.getVersion(), now, user); diagnosisDao.update(diagnosis); } ProcedureDao procedureDao = this.getProcedureDao(); Iterator<Procedure> proceduresIt = proband.getProcedures().iterator(); while (proceduresIt.hasNext()) { Procedure procedure = proceduresIt.next(); procedureDao.reEncrypt(procedure, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(procedure, procedure.getVersion(), now, user); procedureDao.update(procedure); } MoneyTransferDao moneyTransferDao = this.getMoneyTransferDao(); Iterator<MoneyTransfer> moneyTransfersIt = proband.getMoneyTransfers().iterator(); while (moneyTransfersIt.hasNext()) { MoneyTransfer moneyTransfer = moneyTransfersIt.next(); moneyTransferDao.reEncrypt(moneyTransfer, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(moneyTransfer, moneyTransfer.getVersion(), now, user); moneyTransferDao.update(moneyTransfer); } BankAccountDao bankAccountDao = this.getBankAccountDao(); Iterator<BankAccount> bankAccountIt = proband.getBankAccounts().iterator(); while (bankAccountIt.hasNext()) { BankAccount bankAccount = bankAccountIt.next(); bankAccountDao.reEncrypt(bankAccount, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(bankAccount, bankAccount.getVersion(), now, user); bankAccountDao.update(bankAccount); } //no re-encryption for proband list status entries, as those are encryted by the creating user // Iterator<ProbandListEntry> trialParticipationsIt = proband.getTrialParticipations().iterator(); // while (trialParticipationsIt.hasNext()) { // Iterator<ProbandListStatusEntry> probandListStatusEntriesIt = trialParticipationsIt.next().getStatusEntries().iterator(); // while (probandListStatusEntriesIt.hasNext()) { // ProbandListStatusEntry probandListStatusEntry = probandListStatusEntriesIt.next(); // probandListStatusEntryDao.reEncrypt(probandListStatusEntry, oldDepartmentKey, newDepartmentKey); // CoreUtil.modifyVersion(probandListStatusEntry,probandListStatusEntry.getVersion(), now, user); // probandListStatusEntryDao.update(probandListStatusEntry); MassMailRecipientDao massMailRecipientDao = this.getMassMailRecipientDao(); Iterator<MassMailRecipient> massMailReceiptsIt = proband.getMassMailReceipts().iterator(); while (massMailReceiptsIt.hasNext()) { MassMailRecipient recipient = massMailReceiptsIt.next(); massMailRecipientDao.reEncrypt(recipient, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(recipient, recipient.getVersion(), now, user); massMailRecipientDao.update(recipient); } //no re-encryption for journal entries, as those are encryted by the creating user //JournalEntryDao journalEntryDao = this.getJournalEntryDao(); //Iterator<JournalEntry> journalEntriesIt = proband.getJournalEntries().iterator(); //while (journalEntriesIt.hasNext()) { // JournalEntry journalEntry = journalEntriesIt.next(); // journalEntryDao.reEncrypt(journalEntry, oldDepartmentKey, newDepartmentKey); // CoreUtil.modifyVersion(journalEntry, journalEntry.getVersion(), now, user); // journalEntryDao.update(journalEntry); FileDao fileDao = this.getFileDao(); Iterator<File> filesIt = proband.getFiles().iterator(); while (filesIt.hasNext()) { File file = filesIt.next(); fileDao.reEncrypt(file, oldDepartmentKey, newDepartmentKey); CoreUtil.modifyVersion(file, file.getVersion(), now, user); fileDao.update(file); } ServiceUtil.logSystemMessage(proband, result, now, user, SystemMessageCodes.PROBAND_DEPARTMENT_UPDATED, result, original, this.getJournalEntryDao()); return result; } else { throw L10nUtil.initServiceException(ServiceExceptionCodes.PROBAND_DEPARTMENT_NOT_CHANGED); } } }
package de.dentrassi.osgi.web.servlet; import java.net.MalformedURLException; import java.net.URL; import java.util.HashSet; import java.util.Set; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletRegistration.Dynamic; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.dentrassi.osgi.web.DispatcherServlet; public class ContextImpl extends WebAppContext { private final static Logger logger = LoggerFactory.getLogger ( ContextImpl.class ); private final BundleContext context; private final TagDirTracker tagdirTracker; private final TagLibTracker taglibTracker; private FilterTracker filterTracker; public ContextImpl () { this.context = FrameworkUtil.getBundle ( ContextImpl.class ).getBundleContext (); this.tagdirTracker = new TagDirTracker ( this.context ); this.taglibTracker = new TagLibTracker ( this.context ); } @Override public void preConfigure () throws Exception { super.preConfigure (); final ServletHolder holder = addServlet ( DispatcherServlet.class, "/" ); final Dynamic reg = holder.getRegistration (); final long maxLen = Long.getLong ( "drone.web.maxRequestBytes", /* 1GB */1024 * 1024 * 1024 ); final int fileThreshold = Integer.getInteger ( "drone.web.fileThresholdBytes", /* 1MB */1024 * 1024 ); reg.setMultipartConfig ( new MultipartConfigElement ( "", maxLen, maxLen, fileThreshold ) ); this.filterTracker = new FilterTracker ( this.context, getServletContext () ); // filter final javax.servlet.FilterRegistration.Dynamic filter = getServletContext ().addFilter ( "filterTracker", this.filterTracker );
package com.ca.syndicate.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ca.syndicate.example.DeviceSensor; /** * Servlet implementation class TestServlet */ @WebServlet("/SimpleServlet") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SimpleServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleRequest(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { handleRequest(request, response); } /** * * @param request * @param response * @throws IOException */ public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); if ("/test".equals(request.getServletPath())) { response.getWriter().write(getTestResult()); } if ("/status".equals(request.getServletPath())) { response.getWriter().write(getStatus()); } else if ("/alerts".equals(request.getServletPath())) { response.getWriter().write(getAlerts()); } else if ("/report".equals(request.getServletPath())) { response.getWriter().write(runReport()); } response.setStatus(200); } catch (Exception e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } public static String getTestResult() { System.out.println("Test result executed"); //pass case return "{ state: 'ok', pass: true, passed: 1, failed: 0 }"; //failed case //return "{ state: 'ok', pass: false, passed: 0, failed: 1 }"; } public static String getStatus() { return "OK"; } public static String getAlerts() { return "alerts: 1"; } private String runReport() { return DeviceSensor.scan("d1", "floor1"); } }
package com.quexten.ravtech.dk.ui.packaging; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.utils.Array; import com.kotcrab.vis.ui.VisUI; import com.kotcrab.vis.ui.util.highlight.Highlighter; import com.kotcrab.vis.ui.util.highlight.WordHighlightRule; import com.kotcrab.vis.ui.widget.HighlightTextArea; import com.kotcrab.vis.ui.widget.ScrollableTextArea; import com.kotcrab.vis.ui.widget.VisTable; import com.kotcrab.vis.ui.widget.VisTextArea; public class BuildReporterDialog extends VisTable { public Array<PrinterListener> printerListeners = new Array<PrinterListener>(); HighlightTextArea textArea; public BuildReporterDialog () { textArea = new HighlightTextArea(""); textArea.setDisabled(true); Highlighter highlighter = new Highlighter(); highlighter.addRule(new WordHighlightRule(Color.GREEN, "BUILD SUCCESSFUL")); textArea.setHighlighter(highlighter); this.add(textArea).grow(); } public void log (String string) { Gdx.app.log("BuildReporterDialog", string); for (int i = 0; i < printerListeners.size; i++) printerListeners.get(i).onPrint(string); textArea.setText(textArea.getText() + string + "\n"); } public void logError (String message) { Gdx.app.error("BuildReporterDialog", message); textArea.setText(textArea.getText() + "[Error]" + message + "\n"); } @Override public float getPrefHeight () { return textArea.getLines() * VisUI.getSkin().getFont("default-font").getLineHeight(); } }
package elki.evaluation.clustering; import java.util.Collection; import java.util.List; import elki.clustering.ClusteringAlgorithm; import elki.clustering.trivial.ByLabelOrAllInOneClustering; import elki.clustering.trivial.ReferenceClustering; import elki.data.Cluster; import elki.data.Clustering; import elki.database.Database; import elki.database.ids.DBIDUtil; import elki.database.ids.DoubleDBIDList; import elki.evaluation.Evaluator; import elki.evaluation.scores.ScoreEvaluation; import elki.evaluation.scores.adapter.DBIDsTest; import elki.evaluation.scores.adapter.DistanceResultAdapter; import elki.logging.Logging; import elki.math.MeanVariance; import elki.result.EvaluationResult; import elki.result.Metadata; import elki.result.ResultUtil; import elki.utilities.io.FormatUtil; import elki.utilities.optionhandling.Parameterizer; import elki.utilities.optionhandling.OptionID; import elki.utilities.optionhandling.parameterization.Parameterization; import elki.utilities.optionhandling.parameters.Flag; import elki.utilities.optionhandling.parameters.ObjectParameter; /** * Evaluate a clustering result by comparing it to an existing cluster label. * * @author Erich Schubert * @since 0.4.0 * * @opt nodefillcolor LemonChiffon * @assoc - evaluates - Clustering * @composed - - - ClusterContingencyTable * @navhas - create - EvaluateClustering.ScoreResult */ public class EvaluateClustering implements Evaluator { /** * Logger for debug output. */ private static final Logging LOG = Logging.getLogger(EvaluateClustering.class); /** * Reference algorithm. */ private ClusteringAlgorithm<?> referencealg; /** * Apply special handling to noise "clusters". */ private boolean noiseSpecialHandling; /** * Use self-pairing in pair-counting measures */ private boolean selfPairing; /** * Constructor. * * @param referencealg Reference clustering * @param noiseSpecialHandling Noise handling flag * @param selfPairing Self-pairing flag */ public EvaluateClustering(ClusteringAlgorithm<?> referencealg, boolean noiseSpecialHandling, boolean selfPairing) { super(); this.referencealg = referencealg; this.noiseSpecialHandling = noiseSpecialHandling; this.selfPairing = selfPairing; } /** * Evaluate given a cluster (of positive elements) and a scoring list. * * @param eval Evaluation method * @param clus Cluster object * @param ranking Object ranking * @return Score */ public static double evaluateRanking(ScoreEvaluation eval, Cluster<?> clus, DoubleDBIDList ranking) { return eval.evaluate(new DBIDsTest(DBIDUtil.ensureSet(clus.getIDs())), new DistanceResultAdapter(ranking.iter())); } @Override public void processNewResult(Object newResult) { // We may just have added this result. if(newResult instanceof Clustering && isReferenceResult((Clustering<?>) newResult)) { return; } Database db = ResultUtil.findDatabase(newResult); List<Clustering<?>> crs = Clustering.getClusteringResults(newResult); if(crs == null || crs.isEmpty()) { return; } // Compute the reference clustering Clustering<?> refc = null; // Try to find an existing reference clustering (globally) { Collection<Clustering<?>> cs = ResultUtil.filterResults(db, Clustering.class); for(Clustering<?> test : cs) { if(isReferenceResult(test)) { refc = test; break; } } } // Try to find an existing reference clustering (locally) if(refc == null) { Collection<Clustering<?>> cs = ResultUtil.filterResults(newResult, Clustering.class); for(Clustering<?> test : cs) { if(isReferenceResult(test)) { refc = test; break; } } } if(refc == null) { LOG.debug("Generating a new reference clustering."); Object refres = referencealg.run(db); List<Clustering<?>> refcrs = Clustering.getClusteringResults(refres); if(refcrs.isEmpty()) { LOG.warning("Reference algorithm did not return a clustering result!"); return; } if(refcrs.size() > 1) { LOG.warning("Reference algorithm returned more than one result!"); } refc = refcrs.get(0); } else { LOG.debug("Using existing clustering: " + Metadata.of(refc).getLongName()); } for(Clustering<?> c : crs) { if(c == refc) { continue; } evaluteResult(db, c, refc); } } /** * Evaluate a clustering result. * * @param db Database * @param c Clustering * @param refc Reference clustering */ protected void evaluteResult(Database db, Clustering<?> c, Clustering<?> refc) { ClusterContingencyTable contmat = new ClusterContingencyTable(selfPairing, noiseSpecialHandling); contmat.process(refc, c); ScoreResult sr = new ScoreResult(contmat); sr.addHeader(Metadata.of(c).getLongName()); Metadata.hierarchyOf(c).addChild(sr); } /** * Test if a clustering result is a valid reference result. * * @param t Clustering to test. * @return {@code true} if it is considered to be a reference result. */ private boolean isReferenceResult(Clustering<?> t) { return t instanceof ReferenceClustering; } /** * Result object for outlier score judgements. * * @author Erich Schubert * * @composed - - - ClusterContingencyTable */ public static class ScoreResult extends EvaluationResult { /** * Cluster contingency table */ protected ClusterContingencyTable contmat; /** * Constructor. * * @param contmat score result */ public ScoreResult(ClusterContingencyTable contmat) { super(); Metadata.of(this).setLongName("Clustering Evaluation"); this.contmat = contmat; PairCounting paircount = contmat.getPaircount(); MeasurementGroup g = newGroup("Pair counting measures"); g.addMeasure("Jaccard", paircount.jaccard(), 0, 1, false); g.addMeasure("F1-Measure", paircount.f1Measure(), 0, 1, false); g.addMeasure("Precision", paircount.precision(), 0, 1, false); g.addMeasure("Recall", paircount.recall(), 0, 1, false); g.addMeasure("Rand", paircount.randIndex(), 0, 1, false); g.addMeasure("ARI", paircount.adjustedRandIndex(), 0, 1, false); g.addMeasure("FowlkesMallows", paircount.fowlkesMallows(), 0, 1, false); Entropy entropy = contmat.getEntropy(); g = newGroup("Entropy based measures"); g.addMeasure("NMI Joint", entropy.entropyNMIJoint(), 0, 1, false); g.addMeasure("NMI Sqrt", entropy.entropyNMISqrt(), 0, 1, false); BCubed bcubed = contmat.getBCubed(); g = newGroup("BCubed-based measures"); g.addMeasure("F1-Measure", bcubed.f1Measure(), 0, 1, false); g.addMeasure("Recall", bcubed.recall(), 0, 1, false); g.addMeasure("Precision", bcubed.precision(), 0, 1, false); SetMatchingPurity setm = contmat.getSetMatching(); g = newGroup("Set-Matching-based measures"); g.addMeasure("F1-Measure", setm.f1Measure(), 0, 1, false); g.addMeasure("Purity", setm.purity(), 0, 1, false); g.addMeasure("Inverse Purity", setm.inversePurity(), 0, 1, false); EditDistance edit = contmat.getEdit(); g = newGroup("Editing-distance measures"); g.addMeasure("F1-Measure", edit.f1Measure(), 0, 1, false); g.addMeasure("Precision", edit.editDistanceFirst(), 0, 1, false); g.addMeasure("Recall", edit.editDistanceSecond(), 0, 1, false); MeanVariance gini = contmat.averageSymmetricGini(); g = newGroup("Gini measures"); g.addMeasure("Mean +-" + FormatUtil.NF4.format(gini.getCount() > 1. ? gini.getSampleStddev() : 0.), gini.getMean(), 0, 1, false); } /** * Get the contingency table * * @return the contingency table */ public ClusterContingencyTable getContingencyTable() { return contmat; } @Override public boolean visualizeSingleton() { return true; } } /** * Parameterization class. * * @author Erich Schubert */ public static class Par implements Parameterizer { /** * Parameter to obtain the reference clustering. Defaults to a flat label * clustering. */ public static final OptionID REFERENCE_ID = new OptionID("paircounting.reference", "Reference clustering to compare with. Defaults to a by-label clustering."); /** * Parameter flag for special noise handling. */ public static final OptionID NOISE_ID = new OptionID("paircounting.noisespecial", "Use special handling for noise clusters."); /** * Parameter flag to disable self-pairing */ public static final OptionID SELFPAIR_ID = new OptionID("paircounting.selfpair", "Enable self-pairing for cluster comparison."); /** * Reference algorithm. */ private ClusteringAlgorithm<?> referencealg; /** * Apply special handling to noise "clusters". */ private boolean noiseSpecialHandling; /** * Use self-pairing in pair-counting measures */ private boolean selfPairing; @Override public void configure(Parameterization config) { new ObjectParameter<ClusteringAlgorithm<?>>(REFERENCE_ID, ClusteringAlgorithm.class, ByLabelOrAllInOneClustering.class) .grab(config, x -> referencealg = x); new Flag(NOISE_ID).grab(config, x -> noiseSpecialHandling = x); new Flag(SELFPAIR_ID).grab(config, x -> selfPairing = x); } @Override public EvaluateClustering make() { return new EvaluateClustering(referencealg, noiseSpecialHandling, !selfPairing); } } }
package com.jme3.scene.plugins.blender.materials; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import com.jme3.material.Material; import com.jme3.material.RenderState.BlendMode; import com.jme3.material.RenderState.FaceCullMode; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector2f; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Geometry; import com.jme3.scene.VertexBuffer; import com.jme3.scene.VertexBuffer.Format; import com.jme3.scene.VertexBuffer.Usage; import com.jme3.scene.plugins.blender.BlenderContext; import com.jme3.scene.plugins.blender.exceptions.BlenderFileException; import com.jme3.scene.plugins.blender.file.DynamicArray; import com.jme3.scene.plugins.blender.file.Pointer; import com.jme3.scene.plugins.blender.file.Structure; import com.jme3.scene.plugins.blender.materials.MaterialHelper.DiffuseShader; import com.jme3.scene.plugins.blender.materials.MaterialHelper.SpecularShader; import com.jme3.scene.plugins.blender.textures.CombinedTexture; import com.jme3.scene.plugins.blender.textures.TextureHelper; import com.jme3.scene.plugins.blender.textures.blending.TextureBlender; import com.jme3.scene.plugins.blender.textures.blending.TextureBlenderFactory; import com.jme3.texture.Texture; import com.jme3.util.BufferUtils; /** * This class holds the data about the material. * @author Marcin Roguski (Kaelthas) */ public final class MaterialContext { private static final Logger LOGGER = Logger.getLogger(MaterialContext.class.getName()); // texture mapping types public static final int MTEX_COL = 0x01; public static final int MTEX_NOR = 0x02; public static final int MTEX_SPEC = 0x04; public static final int MTEX_EMIT = 0x40; public static final int MTEX_ALPHA = 0x80; public static final int MTEX_AMB = 0x800; /* package */final String name; /* package */final Map<Number, CombinedTexture> loadedTextures; /* package */final ColorRGBA diffuseColor; /* package */final DiffuseShader diffuseShader; /* package */final SpecularShader specularShader; /* package */final ColorRGBA specularColor; /* package */final ColorRGBA ambientColor; /* package */final float shininess; /* package */final boolean shadeless; /* package */final boolean vertexColor; /* package */final boolean transparent; /* package */final boolean vTangent; /* package */FaceCullMode faceCullMode; @SuppressWarnings("unchecked") /* package */MaterialContext(Structure structure, BlenderContext blenderContext) throws BlenderFileException { name = structure.getName(); int mode = ((Number) structure.getFieldValue("mode")).intValue(); shadeless = (mode & 0x4) != 0; vertexColor = (mode & 0x80) != 0; vTangent = (mode & 0x4000000) != 0; // NOTE: Requires tangents int diff_shader = ((Number) structure.getFieldValue("diff_shader")).intValue(); diffuseShader = DiffuseShader.values()[diff_shader]; if (this.shadeless) { float r = ((Number) structure.getFieldValue("r")).floatValue(); float g = ((Number) structure.getFieldValue("g")).floatValue(); float b = ((Number) structure.getFieldValue("b")).floatValue(); float alpha = ((Number) structure.getFieldValue("alpha")).floatValue(); diffuseColor = new ColorRGBA(r, g, b, alpha); specularShader = null; specularColor = ambientColor = null; shininess = 0.0f; } else { diffuseColor = this.readDiffuseColor(structure, diffuseShader); int spec_shader = ((Number) structure.getFieldValue("spec_shader")).intValue(); specularShader = SpecularShader.values()[spec_shader]; specularColor = this.readSpecularColor(structure, specularShader); float shininess = ((Number) structure.getFieldValue("har")).floatValue();//this is (probably) the specular hardness in blender this.shininess = shininess > 0.0f ? shininess : MaterialHelper.DEFAULT_SHININESS; float r = ((Number) structure.getFieldValue("ambr")).floatValue(); float g = ((Number) structure.getFieldValue("ambg")).floatValue(); float b = ((Number) structure.getFieldValue("ambb")).floatValue(); float alpha = ((Number) structure.getFieldValue("alpha")).floatValue(); ambientColor = new ColorRGBA(r, g, b, alpha); } DynamicArray<Pointer> mtexsArray = (DynamicArray<Pointer>) structure.getFieldValue("mtex"); int separatedTextures = ((Number) structure.getFieldValue("septex")).intValue(); List<TextureData> texturesList = new ArrayList<TextureData>(); for (int i = 0; i < mtexsArray.getTotalSize(); ++i) { Pointer p = mtexsArray.get(i); if (p.isNotNull() && (separatedTextures & 1 << i) == 0) { TextureData textureData = new TextureData(); textureData.mtex = p.fetchData(blenderContext.getInputStream()).get(0); textureData.uvCoordinatesType = ((Number) textureData.mtex.getFieldValue("texco")).intValue(); textureData.projectionType = ((Number) textureData.mtex.getFieldValue("mapping")).intValue(); textureData.uvCoordinatesName = textureData.mtex.getFieldValue("uvName").toString(); if(textureData.uvCoordinatesName != null && textureData.uvCoordinatesName.trim().length() == 0) { textureData.uvCoordinatesName = null; } Pointer pTex = (Pointer) textureData.mtex.getFieldValue("tex"); if (pTex.isNotNull()) { Structure tex = pTex.fetchData(blenderContext.getInputStream()).get(0); textureData.textureStructure = tex; texturesList.add(textureData); } } } // loading the textures and merging them Map<Number, List<TextureData>> textureDataMap = this.sortAndFilterTextures(texturesList); loadedTextures = new HashMap<Number, CombinedTexture>(); float[] diffuseColorArray = new float[] { diffuseColor.r, diffuseColor.g, diffuseColor.b, diffuseColor.a }; TextureHelper textureHelper = blenderContext.getHelper(TextureHelper.class); for (Entry<Number, List<TextureData>> entry : textureDataMap.entrySet()) { if (entry.getValue().size() > 0) { CombinedTexture combinedTexture = new CombinedTexture(entry.getKey().intValue()); for (TextureData textureData : entry.getValue()) { int texflag = ((Number) textureData.mtex.getFieldValue("texflag")).intValue(); boolean negateTexture = (texflag & 0x04) != 0; Texture texture = textureHelper.getTexture(textureData.textureStructure, textureData.mtex, blenderContext); if (texture != null) { int blendType = ((Number) textureData.mtex.getFieldValue("blendtype")).intValue(); float[] color = new float[] { ((Number) textureData.mtex.getFieldValue("r")).floatValue(), ((Number) textureData.mtex.getFieldValue("g")).floatValue(), ((Number) textureData.mtex.getFieldValue("b")).floatValue() }; float colfac = ((Number) textureData.mtex.getFieldValue("colfac")).floatValue(); TextureBlender textureBlender = TextureBlenderFactory.createTextureBlender(texture.getImage().getFormat(), texflag, negateTexture, blendType, diffuseColorArray, color, colfac); combinedTexture.add(texture, textureBlender, textureData.uvCoordinatesType, textureData.projectionType, textureData.textureStructure, textureData.uvCoordinatesName, blenderContext); } } if (combinedTexture.getTexturesCount() > 0) { loadedTextures.put(entry.getKey(), combinedTexture); } } } // veryfying if the transparency is present // (in blender transparent mask is 0x10000 but its better to verify it because blender can indicate transparency when // it is not required boolean transparent = false; if (diffuseColor != null) { transparent = diffuseColor.a < 1.0f; if (textureDataMap.size() > 0) {// texutre covers the material color diffuseColor.set(1, 1, 1, 1); } } if (specularColor != null) { transparent = transparent || specularColor.a < 1.0f; } if (ambientColor != null) { transparent = transparent || ambientColor.a < 1.0f; } this.transparent = transparent; } /** * Applies material to a given geometry. * * @param geometry * the geometry * @param geometriesOMA * the geometries OMA * @param userDefinedUVCoordinates * UV coords defined by user * @param blenderContext * the blender context */ public void applyMaterial(Geometry geometry, Long geometriesOMA, LinkedHashMap<String, List<Vector2f>> userDefinedUVCoordinates, BlenderContext blenderContext) { Material material = null; if (shadeless) { material = new Material(blenderContext.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); if (!transparent) { diffuseColor.a = 1; } material.setColor("Color", diffuseColor); } else { material = new Material(blenderContext.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md"); material.setBoolean("UseMaterialColors", Boolean.TRUE); // setting the colors material.setBoolean("Minnaert", diffuseShader == DiffuseShader.MINNAERT); if (!transparent) { diffuseColor.a = 1; } material.setColor("Diffuse", diffuseColor); material.setBoolean("WardIso", specularShader == SpecularShader.WARDISO); material.setColor("Specular", specularColor); material.setFloat("Shininess", shininess); material.setColor("Ambient", ambientColor); } // applying textures if (loadedTextures != null && loadedTextures.size() > 0) { int textureIndex = 0; if(loadedTextures.size() > 8) { LOGGER.log(Level.WARNING, "The blender file has defined more than {0} different textures. JME supports only {0} UV mappings.", TextureHelper.TEXCOORD_TYPES.length); } for (Entry<Number, CombinedTexture> entry : loadedTextures.entrySet()) { if(textureIndex < TextureHelper.TEXCOORD_TYPES.length) { CombinedTexture combinedTexture = entry.getValue(); combinedTexture.flatten(geometry, geometriesOMA, userDefinedUVCoordinates, blenderContext); this.setTexture(material, entry.getKey().intValue(), combinedTexture.getResultTexture()); List<Vector2f> uvs = entry.getValue().getResultUVS(); VertexBuffer uvCoordsBuffer = new VertexBuffer(TextureHelper.TEXCOORD_TYPES[textureIndex++]); uvCoordsBuffer.setupData(Usage.Static, 2, Format.Float, BufferUtils.createFloatBuffer(uvs.toArray(new Vector2f[uvs.size()]))); geometry.getMesh().setBuffer(uvCoordsBuffer); } else { LOGGER.log(Level.WARNING, "The texture could not be applied because JME only supports up to {0} different UV's.", TextureHelper.TEXCOORD_TYPES.length); } } } // applying additional data material.setName(name); if (vertexColor) { material.setBoolean(shadeless ? "VertexColor" : "UseVertexColor", true); } material.getAdditionalRenderState().setFaceCullMode(faceCullMode != null ? faceCullMode : blenderContext.getBlenderKey().getFaceCullMode()); if (transparent) { material.setTransparent(true); material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha); geometry.setQueueBucket(Bucket.Transparent); } geometry.setMaterial(material); } /** * Sets the texture to the given material. * * @param material * the material that we add texture to * @param mapTo * the texture mapping type * @param texture * the added texture */ private void setTexture(Material material, int mapTo, Texture texture) { switch (mapTo) { case MTEX_COL: material.setTexture(shadeless ? MaterialHelper.TEXTURE_TYPE_COLOR : MaterialHelper.TEXTURE_TYPE_DIFFUSE, texture); break; case MTEX_NOR: material.setTexture(MaterialHelper.TEXTURE_TYPE_NORMAL, texture); break; case MTEX_SPEC: material.setTexture(MaterialHelper.TEXTURE_TYPE_SPECULAR, texture); break; case MTEX_EMIT: material.setTexture(MaterialHelper.TEXTURE_TYPE_GLOW, texture); break; case MTEX_ALPHA: if (!shadeless) { material.setTexture(MaterialHelper.TEXTURE_TYPE_ALPHA, texture); } else { LOGGER.warning("JME does not support alpha map on unshaded material. Material name is " + name); } break; case MTEX_AMB: material.setTexture(MaterialHelper.TEXTURE_TYPE_LIGHTMAP, texture); break; default: LOGGER.severe("Unknown mapping type: " + mapTo); } } /** * @return <b>true</b> if the material has at least one generated texture and <b>false</b> otherwise */ public boolean hasGeneratedTextures() { if (loadedTextures != null) { for (Entry<Number, CombinedTexture> entry : loadedTextures.entrySet()) { if (entry.getValue().hasGeneratedTextures()) { return true; } } } return false; } /** * This method sorts the textures by their mapping type. In each group only * textures of one type are put (either two- or three-dimensional). If the * mapping type is MTEX_COL then if the texture has no alpha channel then * all textures before it are discarded and will not be loaded and merged * because texture with no alpha will cover them anyway. * * @return a map with sorted and filtered textures */ private Map<Number, List<TextureData>> sortAndFilterTextures(List<TextureData> textures) { int[] mappings = new int[] { MTEX_COL, MTEX_NOR, MTEX_EMIT, MTEX_SPEC, MTEX_ALPHA, MTEX_AMB }; Map<Number, List<TextureData>> result = new HashMap<Number, List<TextureData>>(); for (TextureData data : textures) { Number mapto = (Number) data.mtex.getFieldValue("mapto"); for (int i = 0; i < mappings.length; ++i) { if ((mappings[i] & mapto.intValue()) != 0) { List<TextureData> datas = result.get(mappings[i]); if (datas == null) { datas = new ArrayList<TextureData>(); result.put(mappings[i], datas); } datas.add(data); } } } return result; } /** * This method sets the face cull mode. * @param faceCullMode * the face cull mode */ public void setFaceCullMode(FaceCullMode faceCullMode) { this.faceCullMode = faceCullMode; } /** * This method returns the diffuse color. * * @param materialStructure * the material structure * @param diffuseShader * the diffuse shader * @return the diffuse color */ private ColorRGBA readDiffuseColor(Structure materialStructure, DiffuseShader diffuseShader) { // bitwise 'or' of all textures mappings int commonMapto = ((Number) materialStructure.getFieldValue("mapto")).intValue(); // diffuse color float r = ((Number) materialStructure.getFieldValue("r")).floatValue(); float g = ((Number) materialStructure.getFieldValue("g")).floatValue(); float b = ((Number) materialStructure.getFieldValue("b")).floatValue(); float alpha = ((Number) materialStructure.getFieldValue("alpha")).floatValue(); if ((commonMapto & 0x01) == 0x01) {// Col return new ColorRGBA(r, g, b, alpha); } else { switch (diffuseShader) { case FRESNEL: case ORENNAYAR: case TOON: break;// TODO: find what is the proper modification case MINNAERT: case LAMBERT:// TODO: check if that is correct float ref = ((Number) materialStructure.getFieldValue("ref")).floatValue(); r *= ref; g *= ref; b *= ref; break; default: throw new IllegalStateException("Unknown diffuse shader type: " + diffuseShader.toString()); } return new ColorRGBA(r, g, b, alpha); } } /** * This method returns a specular color used by the material. * * @param materialStructure * the material structure filled with data * @return a specular color used by the material */ private ColorRGBA readSpecularColor(Structure materialStructure, SpecularShader specularShader) { float r = ((Number) materialStructure.getFieldValue("specr")).floatValue(); float g = ((Number) materialStructure.getFieldValue("specg")).floatValue(); float b = ((Number) materialStructure.getFieldValue("specb")).floatValue(); float alpha = ((Number) materialStructure.getFieldValue("alpha")).floatValue(); switch (specularShader) { case BLINN: case COOKTORRENCE: case TOON: case WARDISO:// TODO: find what is the proper modification break; case PHONG:// TODO: check if that is correct float spec = ((Number) materialStructure.getFieldValue("spec")).floatValue(); r *= spec * 0.5f; g *= spec * 0.5f; b *= spec * 0.5f; break; default: throw new IllegalStateException("Unknown specular shader type: " + specularShader.toString()); } return new ColorRGBA(r, g, b, alpha); } private static class TextureData { Structure mtex; Structure textureStructure; int uvCoordinatesType; int projectionType; /** The name of the user's UV coordinates that are used for this texture. */ String uvCoordinatesName; } }
package de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints; import java.util.List; import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.UnusedParameterException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.AbstractParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Parameter; /** * Global parameter constraint describing the dependency of a parameter ( * {@link AbstractParameter}) on a given flag ({@link Flag}). Depending on the * status of the flag the parameter is tested for keeping its constraints or * not. * * @author Steffi Wanka * * @apiviz.uses de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag * @apiviz.uses * de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Parameter * * @param <S> Parameter type */ public class ParameterFlagGlobalConstraint<S> implements GlobalParameterConstraint { /** * Parameter possibly to be checked. */ private Parameter<? extends S> param; /** * Flag the checking of the parameter constraints is dependent on. */ private Flag flag; /** * Indicates at which status of the flag the parameter is to be checked. */ private boolean flagConstraint; /** * List of parameter constraints. */ private List<? extends ParameterConstraint<? super S>> cons; /** * Constructs a global parameter constraint specifying that the testing of the * parameter given for keeping the parameter constraints given is dependent on * the status of the flag given. * * @param p parameter possibly to be checked * @param c a list of parameter constraints, if the value is null, the * parameter is just tested if it is set. * @param f flag controlling the checking of the parameter constraints * @param flagConstraint indicates at which status of the flag the parameter * is to be checked */ public ParameterFlagGlobalConstraint(Parameter<? extends S> p, List<? extends ParameterConstraint<? super S>> c, Flag f, boolean flagConstraint) { param = p; flag = f; this.flagConstraint = flagConstraint; cons = c; } /** * Checks the parameter for its parameter constraints dependent on the status * of the given flag. If a parameter constraint is breached a parameter * exception is thrown. * */ @Override public void test() throws ParameterException { // only check constraints of param if flag is set if(flagConstraint == flag.getValue().booleanValue()) { if(cons != null) { for(ParameterConstraint<? super S> c : cons) { c.test(param.getValue()); } } else { if(!param.isDefined()) { throw new UnusedParameterException("Value of parameter " + param.getName() + " is not optional."); } } } } @Override public String getDescription() { StringBuilder description = new StringBuilder(); if(flagConstraint) { description.append("If ").append(flag.getName()); description.append(" is set, the following constraints for parameter "); description.append(param.getName()).append(" have to be fullfilled: "); if(cons != null) { for(int i = 0; i < cons.size(); i++) { ParameterConstraint<? super S> c = cons.get(i); if(i > 0) { description.append(", "); } description.append(c.getDescription(param.getName())); } } else { description.append(param.getName()).append(" must be set."); } } return description.toString(); } }
package net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.util.Base64; import java.util.Date; import java.util.LinkedList; import java.util.logging.Logger; import java.util.zip.DataFormatException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.google.common.base.Strings; import net.sf.mzmine.datamodel.DataPoint; import net.sf.mzmine.datamodel.MZmineProject; import net.sf.mzmine.datamodel.MassSpectrumType; import net.sf.mzmine.datamodel.PolarityType; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.RawDataFileWriter; import net.sf.mzmine.datamodel.impl.SimpleDataPoint; import net.sf.mzmine.datamodel.impl.SimpleScan; import net.sf.mzmine.taskcontrol.AbstractTask; import net.sf.mzmine.taskcontrol.TaskStatus; import net.sf.mzmine.util.CompressionUtils; import net.sf.mzmine.util.ExceptionUtils; import net.sf.mzmine.util.scans.ScanUtils; public class MzXMLReadTask extends AbstractTask { private Logger logger = Logger.getLogger(this.getClass().getName()); private File file; private MZmineProject project; private RawDataFileWriter newMZmineFile; private RawDataFile finalRawDataFile; private int totalScans = 0, parsedScans; private int peaksCount = 0; private StringBuilder charBuffer; private boolean compressFlag = false; private DefaultHandler handler = new MzXMLHandler(); private String precision; // Retention time parser private DatatypeFactory dataTypeFactory; /* * This variables are used to set the number of fragments that one single scan can have. The * initial size of array is set to 10, but it depends of fragmentation level. */ private int parentTreeValue[] = new int[10]; private int msLevelTree = 0; /* * This stack stores the current scan and all his fragments until all the information is recover. * The logic is FIFO at the moment of write into the RawDataFile */ private LinkedList<SimpleScan> parentStack; /* * This variable hold the present scan or fragment, it is send to the stack when another * scan/fragment appears as a parser.startElement */ private SimpleScan buildingScan; public MzXMLReadTask(MZmineProject project, File fileToOpen, RawDataFileWriter newMZmineFile) { // 256 kilo-chars buffer charBuffer = new StringBuilder(1 << 18); parentStack = new LinkedList<SimpleScan>(); this.project = project; this.file = fileToOpen; this.newMZmineFile = newMZmineFile; } /** * @see net.sf.mzmine.taskcontrol.Task#getFinishedPercentage() */ public double getFinishedPercentage() { return totalScans == 0 ? 0 : (double) parsedScans / totalScans; } /** * @see java.lang.Runnable#run() */ public void run() { setStatus(TaskStatus.PROCESSING); logger.info("Started parsing file " + file); // Use the default (non-validating) parser SAXParserFactory factory = SAXParserFactory.newInstance(); try { dataTypeFactory = DatatypeFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(file, handler); // Close file finalRawDataFile = newMZmineFile.finishWriting(); project.addFile(finalRawDataFile); } catch (Throwable e) { e.printStackTrace(); /* we may already have set the status to CANCELED */ if (getStatus() == TaskStatus.PROCESSING) { setStatus(TaskStatus.ERROR); setErrorMessage(ExceptionUtils.exceptionToString(e)); } return; } if (isCanceled()) return; if (parsedScans == 0) { setStatus(TaskStatus.ERROR); setErrorMessage("No scans found"); return; } logger.info("Finished parsing " + file + ", parsed " + parsedScans + " scans"); setStatus(TaskStatus.FINISHED); } public String getTaskDescription() { return "Opening file " + file; } private class MzXMLHandler extends DefaultHandler { public void startElement(String namespaceURI, String lName, // local // name String qName, // qualified name Attributes attrs) throws SAXException { if (isCanceled()) throw new SAXException("Parsing Cancelled"); // <msRun> if (qName.equals("msRun")) { String s = attrs.getValue("scanCount"); if (s != null) totalScans = Integer.parseInt(s); } // <scan> if (qName.equalsIgnoreCase("scan")) { if (buildingScan != null) { parentStack.addFirst(buildingScan); buildingScan = null; } /* * Only num, msLevel & peaksCount values are required according with mzxml standard, the * others are optional */ int scanNumber = Integer.parseInt(attrs.getValue("num")); // mzXML files with empty msLevel attribute do exist, so we use 1 as default int msLevel = 1; if (! Strings.isNullOrEmpty(attrs.getValue("msLevel"))) msLevel = Integer.parseInt(attrs.getValue("msLevel")); String scanType = attrs.getValue("scanType"); String filterLine = attrs.getValue("filterLine"); String scanId = filterLine; if (Strings.isNullOrEmpty(scanId)) scanId = scanType; PolarityType polarity; String polarityAttr = attrs.getValue("polarity"); if ((polarityAttr != null) && (polarityAttr.length() == 1)) polarity = PolarityType.fromSingleChar(polarityAttr); else polarity = PolarityType.UNKNOWN; peaksCount = Integer.parseInt(attrs.getValue("peaksCount")); // Parse retention time double retentionTime = 0; String retentionTimeStr = attrs.getValue("retentionTime"); if (retentionTimeStr != null) { Date currentDate = new Date(); Duration dur = dataTypeFactory.newDuration(retentionTimeStr); retentionTime = dur.getTimeInMillis(currentDate) / 1000d / 60d; } else { setStatus(TaskStatus.ERROR); setErrorMessage("This file does not contain retentionTime for scans"); throw new SAXException("Could not read retention time"); } int parentScan = -1; if (msLevel > 9) { setStatus(TaskStatus.ERROR); setErrorMessage("msLevel value bigger than 10"); throw new SAXException("The value of msLevel is bigger than 10"); } if (msLevel > 1) { parentScan = parentTreeValue[msLevel - 1]; for (SimpleScan p : parentStack) { if (p.getScanNumber() == parentScan) { p.addFragmentScan(scanNumber); } } } // Setting the level of fragment of scan and parent scan number msLevelTree++; parentTreeValue[msLevel] = scanNumber; buildingScan = new SimpleScan(null, scanNumber, msLevel, retentionTime, 0, 0, null, new DataPoint[0], null, polarity, scanId, null); } // <peaks> if (qName.equalsIgnoreCase("peaks")) { // clean the current char buffer for the new element charBuffer.setLength(0); compressFlag = false; String compressionType = attrs.getValue("compressionType"); if ((compressionType == null) || (compressionType.equals("none"))) compressFlag = false; else compressFlag = true; precision = attrs.getValue("precision"); } // <precursorMz> if (qName.equalsIgnoreCase("precursorMz")) { // clean the current char buffer for the new element charBuffer.setLength(0); String precursorCharge = attrs.getValue("precursorCharge"); if (precursorCharge != null) buildingScan.setPrecursorCharge(Integer.parseInt(precursorCharge)); } } /** * endElement() */ public void endElement(String namespaceURI, String sName, // simple name String qName // qualified name ) throws SAXException { // </scan> if (qName.equalsIgnoreCase("scan")) { msLevelTree /* * At this point we verify if the scan and his fragments are closed, so we include the * present scan/fragment into the stack and start to take elements from them (FIFO) for the * RawDataFile. */ if (msLevelTree == 0) { parentStack.addFirst(buildingScan); buildingScan = null; while (!parentStack.isEmpty()) { SimpleScan currentScan = parentStack.removeLast(); try { newMZmineFile.addScan(currentScan); } catch (IOException e) { e.printStackTrace(); setStatus(TaskStatus.ERROR); setErrorMessage("IO error: " + e); throw new SAXException("Parsing error: " + e); } parsedScans++; } /* * The scan with all his fragments is in the RawDataFile, now we clean the stack for the * next scan and fragments. */ parentStack.clear(); } return; } // <precursorMz> if (qName.equalsIgnoreCase("precursorMz")) { final String textContent = charBuffer.toString(); double precursorMz = 0d; if (!textContent.isEmpty()) precursorMz = Double.parseDouble(textContent); buildingScan.setPrecursorMZ(precursorMz); return; } // <peaks> if (qName.equalsIgnoreCase("peaks")) { byte[] peakBytes = Base64.getDecoder().decode(charBuffer.toString()); if (compressFlag) { try { peakBytes = CompressionUtils.decompress(peakBytes); } catch (DataFormatException e) { setStatus(TaskStatus.ERROR); setErrorMessage("Corrupt compressed peak: " + e.toString()); throw new SAXException("Parsing Cancelled"); } } // make a data input stream DataInputStream peakStream = new DataInputStream(new ByteArrayInputStream(peakBytes)); DataPoint dataPoints[] = new DataPoint[peaksCount]; try { for (int i = 0; i < dataPoints.length; i++) { // Always respect this order pairOrder="m/z-int" double massOverCharge; double intensity; if ("64".equals(precision)) { massOverCharge = peakStream.readDouble(); intensity = peakStream.readDouble(); } else { massOverCharge = (double) peakStream.readFloat(); intensity = (double) peakStream.readFloat(); } // Copy m/z and intensity data dataPoints[i] = new SimpleDataPoint(massOverCharge, intensity); } } catch (IOException eof) { setStatus(TaskStatus.ERROR); setErrorMessage("Corrupt mzXML file"); throw new SAXException("Parsing Cancelled"); } // Auto-detect whether this scan is centroided MassSpectrumType spectrumType = ScanUtils.detectSpectrumType(dataPoints); // Set the centroided tag buildingScan.setSpectrumType(spectrumType); // Set the final data points to the scan buildingScan.setDataPoints(dataPoints); return; } } /** * characters() * * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ public void characters(char buf[], int offset, int len) throws SAXException { charBuffer.append(buf, offset, len); } } }
package org.cyclops.cyclopscore.modcompat.capabilities; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.Level; import org.cyclops.cyclopscore.helper.Helpers; import org.cyclops.cyclopscore.init.ModBase; import java.util.Collection; import java.util.List; import java.util.Map; public class CapabilityConstructorRegistry { private final Map<Class<? extends TileEntity>, List<ICapabilityConstructor<?, ? extends TileEntity, ? extends TileEntity>>> capabilityConstructorsTile = Maps.newIdentityHashMap(); private final Map<Class<? extends Entity>, List<ICapabilityConstructor<?, ? extends Entity, ? extends Entity>>> capabilityConstructorsEntity = Maps.newIdentityHashMap(); private final Map<Class<? extends Item>, List<ICapabilityConstructor<?, ? extends Item, ? extends ItemStack>>> capabilityConstructorsItem = Maps.newIdentityHashMap(); private Collection<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> capabilityConstructorsTileSuper = Sets.newHashSet(); private Collection<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> capabilityConstructorsEntitySuper = Sets.newHashSet(); private Collection<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> capabilityConstructorsItemSuper = Sets.newHashSet(); protected final ModBase mod; protected boolean baked = false; public CapabilityConstructorRegistry(ModBase mod) { this.mod = mod; MinecraftForge.EVENT_BUS.register(this); } protected ModBase getMod() { return mod; } protected void checkNotBaked() { if (baked) { throw new IllegalStateException("Please register capabilities before pre-init."); } } /** * Register a tile capability constructor. * @param clazz The tile class. * @param constructor The capability constructor. * @param <T> The tile type. */ public <T extends TileEntity> void registerTile(Class<T> clazz, ICapabilityConstructor<?, T, T> constructor) { checkNotBaked(); List<ICapabilityConstructor<?, ? extends TileEntity, ? extends TileEntity>> constructors = capabilityConstructorsTile.get(clazz); if (constructors == null) { constructors = Lists.newArrayList(); capabilityConstructorsTile.put(clazz, constructors); } constructors.add(constructor); } /** * Register an entity capability constructor. * @param clazz The entity class. * @param constructor The capability constructor. * @param <T> The entity type. */ public <T extends Entity> void registerEntity(Class<T> clazz, ICapabilityConstructor<?, T, T> constructor) { checkNotBaked(); List<ICapabilityConstructor<?, ? extends Entity, ? extends Entity>> constructors = capabilityConstructorsEntity.get(clazz); if (constructors == null) { constructors = Lists.newArrayList(); capabilityConstructorsEntity.put(clazz, constructors); } constructors.add(constructor); } /** * Register an item capability constructor. * @param clazz The item class. * @param constructor The capability constructor. * @param <T> The item type. */ public <T extends Item> void registerItem(Class<T> clazz, ICapabilityConstructor<?, T, ItemStack> constructor) { checkNotBaked(); List<ICapabilityConstructor<?, ? extends Item, ? extends ItemStack>> constructors = capabilityConstructorsItem.get(clazz); if (constructors == null) { constructors = Lists.newArrayList(); capabilityConstructorsItem.put(clazz, constructors); } constructors.add(constructor); } /** * Register a tile capability constructor with subtype checking. * Only call this when absolutely required, this will is less efficient than its non-inheritable counterpart. * @param clazz The tile class, all subtypes will be checked. * @param constructor The capability constructor. * @param <K> The capability type. * @param <V> The tile type. */ public <K, V> void registerInheritableTile(Class<K> clazz, ICapabilityConstructor<?, V, V> constructor) { checkNotBaked(); capabilityConstructorsTileSuper.add( Pair.<Class<?>, ICapabilityConstructor<?, ?, ?>>of(clazz, constructor)); } /** * Register an entity capability constructor with subtype checking. * Only call this when absolutely required, this will is less efficient than its non-inheritable counterpart. * @param clazz The tile class, all subtypes will be checked. * @param constructor The capability constructor. * @param <K> The capability type. * @param <V> The entity type. */ public <K, V> void registerInheritableEntity(Class<K> clazz, ICapabilityConstructor<?, V, V> constructor) { checkNotBaked(); capabilityConstructorsEntitySuper.add( Pair.<Class<?>, ICapabilityConstructor<?, ?, ?>>of(clazz, constructor)); } /** * Register an item capability constructor with subtype checking. * Only call this when absolutely required, this will is less efficient than its non-inheritable counterpart. * @param clazz The tile class, all subtypes will be checked. * @param constructor The capability constructor. * @param <T> The tile type. */ public <T> void registerInheritableItem(Class<T> clazz, ICapabilityConstructor<?, ?, ? extends ItemStack> constructor) { checkNotBaked(); capabilityConstructorsItemSuper.add( Pair.<Class<?>, ICapabilityConstructor<?, ?, ?>>of(clazz, constructor)); } @SuppressWarnings("unchecked") protected <K, KE, H, HE> ICapabilityProvider createProvider(KE hostType, HE host, ICapabilityConstructor<?, K, H> capabilityConstructor) { return capabilityConstructor.createProvider((K) hostType, (H) host); } protected <T> void onLoad(Map<Class<? extends T>, List<ICapabilityConstructor<?, ? extends T, ? extends T>>> allConstructors, Collection<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> allInheritableConstructors, T object, AttachCapabilitiesEvent<?> event, Class<? extends T> baseClass) { onLoad(allConstructors, allInheritableConstructors, object, object, event, baseClass); } protected <K, V> void onLoad(Map<Class<? extends K>, List<ICapabilityConstructor<?, ? extends K, ? extends V>>> allConstructors, Collection<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> allInheritableConstructors, K keyObject, V valueObject, AttachCapabilitiesEvent<?> event, Class<? extends K> baseClass) { boolean initialized = baked || Helpers.isMinecraftInitialized(); if (!baked && Helpers.isMinecraftInitialized()) { bake(); } // Normal constructors Collection<ICapabilityConstructor<?, ? extends K, ? extends V>> constructors = allConstructors.get(keyObject.getClass()); if (constructors != null) { for (ICapabilityConstructor<?, ? extends K, ? extends V> constructor : constructors) { if (initialized || constructor.getCapability() != null) { addLoadedCapabilityProvider(event, keyObject, valueObject, constructor); } } } // Inheritable constructors for (Pair<Class<?>, ICapabilityConstructor<?, ?, ?>> constructorEntry : allInheritableConstructors) { if ((initialized || constructorEntry.getRight().getCapability() != null) && (keyObject == baseClass || constructorEntry.getLeft() == keyObject || constructorEntry.getLeft().isInstance(keyObject))) { addLoadedCapabilityProvider(event, keyObject, valueObject, constructorEntry.getRight()); } } } protected <K, V> void addLoadedCapabilityProvider(AttachCapabilitiesEvent<?> event, K keyObject, V valueObject, ICapabilityConstructor<?, ?, ?> constructor) { ICapabilityProvider provider = createProvider(keyObject, valueObject, constructor); if (provider != null) { ResourceLocation id = new ResourceLocation(getMod().getModId(), constructor.getCapability().getName()); if (!event.getCapabilities().containsKey(id)) { event.addCapability(id, provider); } else { getMod().getLoggerHelper().log(Level.DEBUG, "Duplicate capability registration of " + id + " in " + keyObject); } } } @SubscribeEvent public void onTileLoad(AttachCapabilitiesEvent<TileEntity> event) { onLoad(capabilityConstructorsTile, capabilityConstructorsTileSuper, event.getObject(), event, TileEntity.class); } @SubscribeEvent public void onEntityLoad(AttachCapabilitiesEvent<Entity> event) { onLoad(capabilityConstructorsEntity, capabilityConstructorsEntitySuper, event.getObject(), event, Entity.class); } @SubscribeEvent public void onItemStackLoad(AttachCapabilitiesEvent<ItemStack> event) { if (!event.getObject().isEmpty()) { onLoad(capabilityConstructorsItem, capabilityConstructorsItemSuper, event.getObject().getItem(), event.getObject(), event, Item.class); } } protected <K, V> void removeNullCapabilities(Map<Class<? extends K>, List<ICapabilityConstructor<?, ? extends K, ? extends V>>> allConstructors, Collection<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> allInheritableConstructors) { // Normal constructors Multimap<Class<? extends K>, ICapabilityConstructor<?, ? extends K, ? extends V>> toRemoveMap = HashMultimap.create(); for (Class<? extends K> key : allConstructors.keySet()) { Collection<ICapabilityConstructor<?, ? extends K, ? extends V>> constructors = allConstructors.get(key); for (ICapabilityConstructor<?, ? extends K, ? extends V> constructor : constructors) { if (constructor.getCapability() == null) { toRemoveMap.put(key, constructor); } } } for (Map.Entry<Class<? extends K>, ICapabilityConstructor<?, ? extends K, ? extends V>> entry : toRemoveMap.entries()) { List<ICapabilityConstructor<?, ? extends K, ? extends V>> constructors = allConstructors.get(entry.getKey()); constructors.remove(entry.getValue()); } // Inheritable constructors List<Pair<Class<?>, ICapabilityConstructor<?, ?, ?>>> toRemoveInheritableList = Lists.newArrayList(); for (Pair<Class<?>, ICapabilityConstructor<?, ?, ?>> constructorEntry : allInheritableConstructors) { if (constructorEntry.getRight().getCapability() == null) { toRemoveInheritableList.add(constructorEntry); } } for (Pair<Class<?>, ICapabilityConstructor<?, ?, ?>> toRemove : toRemoveInheritableList) { allInheritableConstructors.remove(toRemove); } } /** * Bakes the registry so that it becomes immutable. */ public void bake() { baked = true; // Remove capability constructors for capabilities that are not initialized. removeNullCapabilities(capabilityConstructorsTile, capabilityConstructorsTileSuper); removeNullCapabilities(capabilityConstructorsEntity, capabilityConstructorsEntitySuper); removeNullCapabilities(capabilityConstructorsItem, capabilityConstructorsItemSuper); // Bake all collections capabilityConstructorsTileSuper = ImmutableList.copyOf(capabilityConstructorsTileSuper); capabilityConstructorsEntitySuper = ImmutableList.copyOf(capabilityConstructorsEntitySuper); capabilityConstructorsItemSuper = ImmutableList.copyOf(capabilityConstructorsItemSuper); } }
package org.ihtsdo.buildcloud.service.buildstatuslistener; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import org.ihtsdo.buildcloud.dao.BuildDAO; import org.ihtsdo.buildcloud.entity.Build; import org.ihtsdo.buildcloud.entity.BuildReport; import org.ihtsdo.buildcloud.entity.PreConditionCheckReport; import org.ihtsdo.buildcloud.entity.Product; import org.ihtsdo.buildcloud.service.BuildService; import org.ihtsdo.buildcloud.service.BuildServiceImpl; import org.ihtsdo.buildcloud.service.ProductService; import org.ihtsdo.otf.rest.exception.BadConfigurationException; import org.ihtsdo.otf.rest.exception.EntityAlreadyExistsException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.jms.annotation.JmsListener; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Service; import javax.jms.JMSException; import javax.jms.TextMessage; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @ConditionalOnProperty(name = "srs.manager", havingValue = "true") @Service public class BuildStatusListenerService { private static final Logger LOGGER = LoggerFactory.getLogger(BuildStatusListenerService.class); private static final String PRODUCT_NAME_KEY = "productName"; private static final String PRODUCT_KEY = "productKey"; private static final String RELEASE_CENTER_KEY = "releaseCenterKey"; private static final String PRODUCT_BUSINESS_KEY = "productBusinessKey"; private static final String BUILD_STATUS_KEY = "buildStatus"; private static final String BUILD_ID_KEY = "buildId"; private static final String RUN_ID_KEY = "runId"; private static final String STATE_KEY = "state"; private static final List<String> CONCURRENT_RELEASE_BUILD_MAP_KEYS = Arrays.asList(PRODUCT_NAME_KEY, PRODUCT_BUSINESS_KEY, BUILD_STATUS_KEY); private static final List<String> RVF_STATUS_MAP_KEYS = Arrays.asList(RUN_ID_KEY, STATE_KEY); private static final List<String> STORE_MINI_RVF_VALIDATION_REQUEST_MAP_KEYS = Arrays.asList(RUN_ID_KEY, BUILD_ID_KEY, RELEASE_CENTER_KEY, PRODUCT_KEY); private static final List<String> UPDATE_STATUS_MAP_KEYS = Arrays.asList(RELEASE_CENTER_KEY, PRODUCT_KEY, BUILD_ID_KEY, BUILD_STATUS_KEY); private static final Map<String, String> CONCURRENT_RELEASE_BUILD_MAP = new ConcurrentHashMap<>(); private static final Map<Long, MiniRVFValidationRequest> MINI_RVF_VALIDATION_REQUEST_MAP = new ConcurrentHashMap<>(); @Autowired private BuildService buildService; @Autowired private BuildServiceImpl buildServiceImpl; @Autowired private ProductService productService; @Autowired private SimpMessagingTemplate simpMessagingTemplate; @Autowired private ObjectMapper objectMapper; @SuppressWarnings("unchecked") @JmsListener(destination = "${srs.jms.queue.prefix}.build-job-status") public void consumeBuildStatus(final TextMessage textMessage) { try { if (textMessage != null) { final String text = textMessage.getText(); LOGGER.info("Received message: {}", text); final Map<String, Object> message = objectMapper.readValue(text, Map.class); LOGGER.info("******* 1 *******"); if (propertiesExist(message, CONCURRENT_RELEASE_BUILD_MAP_KEYS)) { LOGGER.info("******* 2 *******"); processConcurrentReleaseBuildMap(message); } else if (propertiesExist(message, RVF_STATUS_MAP_KEYS)) { LOGGER.info("******* 3 *******"); processRVFStatus(message); } else if (propertiesExist(message, STORE_MINI_RVF_VALIDATION_REQUEST_MAP_KEYS)) { LOGGER.info("******* 4 *******"); storeMiniRVFValidationRequest(message); } else if (propertiesExist(message, UPDATE_STATUS_MAP_KEYS)) { LOGGER.info("******* 5 *******"); updateStatus(message); } } } catch (JMSException | JsonProcessingException | BadConfigurationException e) { LOGGER.error("Error occurred while trying to obtain the build status.", e); } } private boolean propertiesExist(final Map<String, Object> message, final List<String> properties) { return properties.stream().allMatch(message::containsKey); } private void processRVFStatus(final Map<String, Object> message) throws JsonProcessingException, BadConfigurationException { LOGGER.info("RVF Message: {}", message); final MiniRVFValidationRequest miniRvfValidationRequest = MINI_RVF_VALIDATION_REQUEST_MAP.get((Long) message.get(RUN_ID_KEY)); final Product product = productService.find(miniRvfValidationRequest.getReleaseCenterKey(), miniRvfValidationRequest.getProductKey(), true); final Build build = buildService.find(product.getReleaseCenter().getBusinessKey(), product.getBusinessKey(), miniRvfValidationRequest.getBuildId(), true, false, true, true); final Build.Status buildStatus = getBuildStatusFromRVF(message, build); String resultStatus = "completed"; String resultMessage = "Process completed successfully"; if (buildStatus != null) { final BuildReport report = build.getBuildReport(); buildServiceImpl.setReportStatusAndPersist(build, buildStatus, report, resultStatus, resultMessage); LOGGER.info("SRS Build Status: {}", buildStatus.name()); updateStatus(ImmutableMap.of(RELEASE_CENTER_KEY, product.getReleaseCenter().getBusinessKey(), PRODUCT_KEY, product.getBusinessKey(), BUILD_ID_KEY, build.getId(), BUILD_STATUS_KEY, buildStatus)); } } private Build.Status getBuildStatusFromRVF(final Map<String, Object> message, final Build build) { final String state = (String) message.get(STATE_KEY); LOGGER.info("State from RVF response: {}", state); switch (state) { case "QUEUED": return Build.Status.RVF_QUEUED; case "RUNNING": return Build.Status.RVF_RUNNING; case "COMPLETE": return processCompleteStatus(build); case "FAILED": return Build.Status.FAILED; default: LOGGER.info("Unexpected build status state: {}", state); return null; } } private Build.Status processCompleteStatus(final Build build) { // Does not check post RVF results. boolean hasWarnings = false; if (build.getPreConditionCheckReports() != null) { hasWarnings = build.getPreConditionCheckReports().stream().anyMatch(conditionCheckReport -> conditionCheckReport.getResult() == PreConditionCheckReport.State.WARNING); } return hasWarnings ? Build.Status.RELEASE_COMPLETE_WITH_WARNINGS : Build.Status.RELEASE_COMPLETE; } private void processConcurrentReleaseBuildMap(final Map<String, Object> message) { final Build.Status buildStatus = Build.Status.findBuildStatus((String) message.get(BUILD_STATUS_KEY)); if (buildStatus != Build.Status.QUEUED && buildStatus != Build.Status.BEFORE_TRIGGER && buildStatus != Build.Status.BUILDING) { final String productBusinessKey = (String) message.get(PRODUCT_KEY); final String productName = (String) message.get(PRODUCT_NAME_KEY); if (productBusinessKey != null && productName != null) { CONCURRENT_RELEASE_BUILD_MAP.remove(productBusinessKey, productName); } } } /** * Fires off message to the web socket. * * @param message Being sent to the web socket. */ private void updateStatus(final Map<String, Object> message) throws JsonProcessingException { simpMessagingTemplate.convertAndSend("/topic/snomed-release-service-websocket", objectMapper.writeValueAsString(message)); } private void storeMiniRVFValidationRequest(final Map<String, Object> message) { LOGGER.info("Message being stored inside RVF validation request map: {}", message); MINI_RVF_VALIDATION_REQUEST_MAP.putIfAbsent((Long) message.get(RUN_ID_KEY), new MiniRVFValidationRequest((String) message.get(BUILD_ID_KEY), (String) message.get(RELEASE_CENTER_KEY), (String) message.get(PRODUCT_KEY))); } /** * Adds the product to the {@code CONCURRENT_RELEASE_BUILD_MAP}. If either * the {@code productBusinessKey} or {@code productName} is null, then the operation will fail gracefully by * exiting the underlying method before the operation has been performed and will * log the relevant message. * * @param productBusinessKey Used as the key entry for the {@code productName} value. * @param productName Value which will reside in the {@code CONCURRENT_RELEASE_BUILD_MAP}. */ public final void addProductToConcurrentReleaseBuildMap(final String productBusinessKey, final String productName) { if (productBusinessKey == null || productName == null) { LOGGER.info("Product business key or product name is null when attempting to add the product to the concurrent release build map."); return; } CONCURRENT_RELEASE_BUILD_MAP.putIfAbsent(productBusinessKey, productName); } /** * Removes the product from the {@code CONCURRENT_RELEASE_BUILD_MAP}. If either * the {@code productBusinessKey} or {@code productName} is null, then the operation will fail gracefully by * exiting the underlying method before the operation has been performed and will * log the relevant message. * * @param productBusinessKey Used to find the product name so that it can be removed. * @param productName Value inside the {@code CONCURRENT_RELEASE_BUILD_MAP} which is going * to be removed, given the {@code productBusinessKey} exists. */ public final void removeProductFromConcurrentReleaseBuildMap(final String productBusinessKey, final String productName) { if (productBusinessKey == null || productName == null) { LOGGER.info("Product business key or product name is null when attempting to remove the product from the concurrent release build map."); return; } CONCURRENT_RELEASE_BUILD_MAP.remove(productBusinessKey, productName); } /** * Throws {@code EntityAlreadyExistsException} if a build is * already in progress for the given product. * * @param productKey Used to determine whether the product already * exists inside the {@code CONCURRENT_RELEASE_BUILD_MAP}. * @param releaseCenter Used to indicate which product has already been started, * in which release center. * @throws EntityAlreadyExistsException If a build is already in progress for * the given product. */ public final void throwExceptionIfBuildIsInProgressForProduct(final String productKey, final String releaseCenter) throws EntityAlreadyExistsException { if (productKey != null && CONCURRENT_RELEASE_BUILD_MAP.containsKey(productKey)) { throw new EntityAlreadyExistsException("Product " + CONCURRENT_RELEASE_BUILD_MAP.get(productKey) + " in release center " + releaseCenter + " has already a in-progress build"); } } }
package org.neptunepowered.vanilla.mixin.minecraft.network; import net.canarymod.Canary; import net.canarymod.api.NetServerHandler; import net.canarymod.api.chat.ChatComponent; import net.canarymod.api.entity.living.humanoid.Player; import net.canarymod.api.packet.Packet; import net.canarymod.hook.player.DisconnectionHook; import net.canarymod.hook.player.KickHook; import net.canarymod.hook.player.PlayerIdleHook; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.S00PacketKeepAlive; import net.minecraft.network.play.server.S02PacketChat; import net.minecraft.network.play.server.S07PacketRespawn; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import org.apache.logging.log4j.Logger; import org.neptunepowered.vanilla.interfaces.minecraft.network.IMixinNetHandlerPlayServer; import org.neptunepowered.vanilla.util.helper.NetHandlerPlayServerHelper; import org.neptunepowered.vanilla.wrapper.chat.NeptuneChatComponent; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import java.net.SocketAddress; @Mixin(NetHandlerPlayServer.class) public abstract class MixinNetHandlerPlayServer implements NetServerHandler, IMixinNetHandlerPlayServer { @Shadow private static Logger logger; @Shadow public NetworkManager netManager; @Shadow public EntityPlayerMP playerEntity; @Shadow private MinecraftServer serverController; @Shadow private int networkTickCount; @Shadow private boolean field_147366_g; @Shadow private int field_147378_h; @Shadow private long lastPingTime; @Shadow private long lastSentPingPacket; @Shadow private int chatSpamThresholdCount; @Shadow private int itemDropThreshold; @Shadow public abstract void sendPacket(final net.minecraft.network.Packet packetIn); @Shadow public abstract long currentTimeMillis(); /** * Overwrite to fire {@link PlayerIdleHook}. * * @author jamierocks */ @Overwrite public void update() { this.field_147366_g = false; ++this.networkTickCount; this.serverController.theProfiler.startSection("keepAlive"); if ((long) this.networkTickCount - this.lastSentPingPacket > 40L) { this.lastSentPingPacket = (long) this.networkTickCount; this.lastPingTime = this.currentTimeMillis(); this.field_147378_h = (int) this.lastPingTime; this.sendPacket(new S00PacketKeepAlive(this.field_147378_h)); } this.serverController.theProfiler.endSection(); if (this.chatSpamThresholdCount > 0) { --this.chatSpamThresholdCount; } if (this.itemDropThreshold > 0) { --this.itemDropThreshold; } long timeIdle = MinecraftServer.getCurrentTimeMillis() - this.playerEntity.getLastActiveTime(); if (this.playerEntity.getLastActiveTime() > 0L && this.serverController.getMaxPlayerIdleMinutes() > 0 && timeIdle > (long) (this.serverController.getMaxPlayerIdleMinutes() * 1000 * 60) && !((Player) this.playerEntity).canIgnoreRestrictions()) { // Neptune - check if player is immune // Neptune - start PlayerIdleHook idleHook = (PlayerIdleHook) new PlayerIdleHook((Player) this.playerEntity, timeIdle).call(); if (!idleHook.isCanceled()) { this.kickPlayerFromServer("You have been idle for too long!"); } // Neptune - end } } /** * Overwrite to fire the KickHook. * * @author jamierocks */ @Overwrite public void kickPlayerFromServer(String reason) { // Fire KickHook new KickHook((Player) this.playerEntity, Canary.getServer(), reason).call(); // Kick player this.kickPlayerFromServerWithoutHook(reason); } /** * Overwrite to fire the DisconnectHook. * * @author jamierocks */ @Overwrite public void onDisconnect(IChatComponent reason) { logger.info(this.playerEntity.getName() + " lost connection: " + reason); this.serverController.refreshStatusNextTick(); ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("multiplayer.player.left", new Object[]{this.playerEntity.getDisplayName()}); chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.YELLOW); // Neptune - start DisconnectionHook hook = (DisconnectionHook) new DisconnectionHook( (Player) this.playerEntity, reason.getUnformattedText(), chatcomponenttranslation.getUnformattedText()).call(); if (!hook.isHidden()) { this.serverController.getConfigurationManager().sendChatMsg(chatcomponenttranslation); } // Neptune - end this.playerEntity.mountEntityAndWakeUp(); this.serverController.getConfigurationManager().playerLoggedOut(this.playerEntity); if (this.serverController.isSinglePlayer() && this.playerEntity.getName().equals(this.serverController.getServerOwner())) { logger.info("Stopping singleplayer server as player logged out"); this.serverController.initiateShutdown(); } } @Override public void sendPacket(Packet packet) { this.sendPacket((net.minecraft.network.Packet) packet); } @Override public void handleChat(Packet chatPacket) { if (!(chatPacket instanceof S02PacketChat)) { return; } this.sendPacket(chatPacket); } @Override public void handleCommand(String[] command) { this.getUser().executeCommand(command); } @Override public void handleRespawn(Packet respawnPacket) { if (!(respawnPacket instanceof S07PacketRespawn)) { return; } this.sendPacket(respawnPacket); } @Override public Player getUser() { return (Player) playerEntity; } @Override public void sendMessage(String message) { this.sendMessage(Canary.factory().getChatComponentFactory().compileChatComponent(message)); } @Override public void sendMessage(ChatComponent chatComponent) { this.sendPacket(new S02PacketChat(((NeptuneChatComponent) chatComponent).getHandle())); } @Override public SocketAddress getSocketAdress() { return this.netManager.getRemoteAddress(); } @Override public void kickPlayerFromServerWithoutHook(String reason) { NetHandlerPlayServerHelper.kickPlayerFromServer(this.playerEntity, reason); } }
package org.mtransit.parser.ca_squamish_transit_system_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.Utils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTripStop; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.mt.data.MTrip; // https://bctransit.com/*/footer/open-data public class SquamishTransitSystemBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-squamish-transit-system-bus-android/res/raw/"; args[2] = ""; // files-prefix } new SquamishTransitSystemBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating Squamish Transit System bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); System.out.printf("\nGenerating Squamish Transit System bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } private static final String INCLUDE_ONLY_SERVICE_ID_CONTAINS = null; @Override public boolean excludeCalendar(GCalendar gCalendar) { if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null && !gCalendar.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) { return true; } if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null && !gCalendarDates.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) { return true; } if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } private static final String INCLUDE_AGENCY_ID = "1"; // Squamish Transit System only @Override public boolean excludeRoute(GRoute gRoute) { if (!INCLUDE_AGENCY_ID.equals(gRoute.getAgencyId())) { return true; } return super.excludeRoute(gRoute); } @Override public boolean excludeTrip(GTrip gTrip) { if (INCLUDE_ONLY_SERVICE_ID_CONTAINS != null && !gTrip.getServiceId().contains(INCLUDE_ONLY_SERVICE_ID_CONTAINS)) { return true; } if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = CleanUtils.cleanSlashes(routeLongName); routeLongName = CleanUtils.cleanNumbers(routeLongName); routeLongName = CleanUtils.cleanStreetTypes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_GREEN = "34B233";// GREEN (from PDF Corporate Graphic Standards) @SuppressWarnings("unused") private static final String AGENCY_COLOR_BLUE = "002C77"; // BLUE (from PDF Corporate Graphic Standards) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteColor())) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 1: return "004B8D"; case 2: return "8CC63F"; case 3: return "F78B1F"; case 4: return "FB298C"; case 5: return "00ADEE"; case 9: return "AB5C3B"; // @formatter:on default: System.out.printf("\nUnexpected route color for %s!\n", gRoute); System.exit(-1); return null; } } return super.getRouteColor(gRoute); } // TRIP DIRECTION ID USED BY REAL-TIME API private static final int COUNTERCLOCKWISE_0 = 0; private static final int COUNTERCLOCKWISE_1 = 1; private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(3L, new RouteTripSpec(3L, COUNTERCLOCKWISE_0, MTrip.HEADSIGN_TYPE_STRING, "Downtown", COUNTERCLOCKWISE_1, MTrip.HEADSIGN_TYPE_STRING, "Valleycliffe") .addTripSort(COUNTERCLOCKWISE_0, Arrays.asList(new String[] { Stops.ALL_STOPS.get("102762"), // Northbound Spruce at Chestnut Stops.ALL_STOPS.get("102749"), // ++ Westway at Cedar (SB) Stops.ALL_STOPS.get("102729"), // Westbound Pemberton at Third #DOWNTOWN })) .addTripSort(COUNTERCLOCKWISE_1, Arrays.asList(new String[] { Stops.ALL_STOPS.get("102729"), // Westbound Pemberton at Third #DOWNTOWN Stops.ALL_STOPS.get("102734"), // == Cleveland at Hunter (EB) Stops.ALL_STOPS.get("102706"), // != Behrner at Clarke (NB) Stops.ALL_STOPS.get("102705"), // != Clarke at Behrner (SB) Stops.ALL_STOPS.get("102747"), // == Guilford at Westway (EB) Stops.ALL_STOPS.get("102762"), // Northbound Spruce at Chestnut })) .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId()); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue()); if (mTrip.getRouteId() == 1L) { if (Arrays.asList( "Garibaldi Vlg", "Downtown" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Downtown", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 2L) { if (Arrays.asList( "Garibaldi Vlg", "Downtown" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Downtown", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 3L) { if (Arrays.asList( "Valleycliffe", "Valleycliffe-Spruce Loop Only" ).containsAll(headsignsValues)) { mTrip.setHeadsignString("Valleycliffe", mTrip.getHeadsignId()); return true; } } System.out.printf("\nUnexpected trips to merge: %s & %s!\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final String EXCH = "Exch"; private static final Pattern EXCHANGE = Pattern.compile("((^|\\W){1}(exchange)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String EXCHANGE_REPLACEMENT = "$2" + EXCH + "$4"; private static final Pattern ENDS_WITH_VIA = Pattern.compile("(( |\\-)via .*$)", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_WITH_TO = Pattern.compile("(^.*to )", Pattern.CASE_INSENSITIVE); private static final Pattern AND = Pattern.compile("( and )", Pattern.CASE_INSENSITIVE); private static final String AND_REPLACEMENT = " & "; private static final Pattern CLEAN_P1 = Pattern.compile("[\\s]*\\([\\s]*"); private static final String CLEAN_P1_REPLACEMENT = " ("; private static final Pattern CLEAN_P2 = Pattern.compile("[\\s]*\\)[\\s]*"); private static final String CLEAN_P2_REPLACEMENT = ") "; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = EXCHANGE.matcher(tripHeadsign).replaceAll(EXCHANGE_REPLACEMENT); tripHeadsign = ENDS_WITH_VIA.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = STARTS_WITH_TO.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = AND.matcher(tripHeadsign).replaceAll(AND_REPLACEMENT); tripHeadsign = CLEAN_P1.matcher(tripHeadsign).replaceAll(CLEAN_P1_REPLACEMENT); tripHeadsign = CLEAN_P2.matcher(tripHeadsign).replaceAll(CLEAN_P2_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern STARTS_WITH_IMPL = Pattern.compile("(^(\\(\\-IMPL\\-\\)))", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_WITH_BOUND = Pattern.compile("(^(east|west|north|south)bound)", Pattern.CASE_INSENSITIVE); @Override public String cleanStopName(String gStopName) { gStopName = STARTS_WITH_IMPL.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = STARTS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = EXCHANGE.matcher(gStopName).replaceAll(EXCHANGE_REPLACEMENT); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } @Override public int getStopId(GStop gStop) { return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID } }
package org.ow2.proactive.resourcemanager.utils.adminconsole; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import org.ow2.proactive.resourcemanager.common.event.RMNodeEvent; import org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent; import org.ow2.proactive.resourcemanager.exception.AddingNodesException; import org.ow2.proactive.resourcemanager.exception.RMException; import org.ow2.proactive.resourcemanager.frontend.RMAdmin; import org.ow2.proactive.resourcemanager.nodesource.common.PluginDescriptor; import org.ow2.proactive.resourcemanager.nodesource.infrastructure.manager.GCMInfrastructure; import org.ow2.proactive.resourcemanager.nodesource.policy.StaticPolicy; import org.ow2.proactive.utils.console.Command; import org.ow2.proactive.utils.console.ConsoleModel; import org.ow2.proactive.utils.console.MBeanInfoViewer; /** * AdminRMModel is the class that drives the RM console in the admin view. * To use this class, get the model, connect a RM and a console, and just start this model. * * @author The ProActive Team * @since ProActive Scheduling 1.0 */ public class AdminRMModel extends ConsoleModel { private static final String JS_INIT_FILE = "AdminActions.js"; protected static final int cmdHelpMaxCharLength = 28; protected RMAdmin rm; private ArrayList<Command> commands; private static int logsNbLines = 20; private static String logsDirectory = System.getProperty("pa.rm.home") + File.separator + ".logs"; private static final String rmLogFile = "RM.log"; protected MBeanInfoViewer jmxInfoViewer = null; /** * Get this model. Also specify if the exit command should do something or not * * @param allowExitCommand true if the exit command is part of the commands, false if exit command does not exist. * @return the current model associated to this class. */ public static AdminRMModel getModel(boolean allowExitCommand) { if (model == null) { model = new AdminRMModel(allowExitCommand); } return (AdminRMModel) model; } private static AdminRMModel getModel() { return (AdminRMModel) model; } protected AdminRMModel(boolean allowExitCommand) { this.allowExitCommand = allowExitCommand; commands = new ArrayList<Command>(); commands .add(new Command( "exMode(display,onDemand)", "Change the way exceptions are displayed (if display is true, stacks are displayed - if onDemand is true, prompt before displaying stacks)")); commands.add(new Command("addnode(nodeURL, nsName)", "Add node to the given node source (parameters is a string representing the node URL to add AND" + " a string representing the node source in which to add the node)")); commands.add(new Command("removenode(nodeURL,preempt)", "Remove the given node (parameter is a string representing the node URL," + " node is removed immediately if second parameter is true)")); commands.add(new Command("createns(nsName,infr,pol)", "Create a new node source with specified name, infrastructure and policy (e.g. createns('myname', ['infrastrucure', 'param1', ...], ['policy', 'param1', ...]))")); commands.add(new Command("removens(nsName,preempt)", "Remove the given node source (parameter is a string representing the node source name to remove," + " nodeSource is removed immediately if second parameter is true)")); commands.add(new Command("listnodes()", "List every handled nodes")); commands.add(new Command("listns()", "List every handled node sources")); commands.add(new Command("listInfrastructures()", "List supported infrastructures")); commands.add(new Command("listPolicies()", "List available node sources policies")); commands.add(new Command("shutdown(preempt)", "Shutdown the Resource Manager (RM shutdown immediately if parameter is true)")); commands.add(new Command("jmxinfo()", "Display some statistics provided by the Scheduler MBean")); commands .add(new Command("exec(scriptFilePath)", "Execute the content of the given script file (parameter is a string representing a script-file path)")); commands.add(new Command("setLogsDir(logsDir)", "Set the directory where the log are located, (default is RM_HOME/.logs")); commands.add(new Command("viewlogs(nbLines)", "View the last nbLines lines of the logs file, (default nbLines is 20)")); if (allowExitCommand) { commands.add(new Command("exit()", "Exits RM controller")); } } /** * @see org.ow2.proactive.utils.console.ConsoleModel#checkIsReady() */ @Override protected void checkIsReady() { super.checkIsReady(); if (rm == null) { throw new RuntimeException("RM is not set, it must be set before starting the model"); } } /** * @see org.ow2.proactive.utils.console.ConsoleModel#initialize() */ @Override protected void initialize() throws IOException { super.initialize(); //read and launch Action.js BufferedReader br = new BufferedReader(new InputStreamReader(AdminController.class .getResourceAsStream(JS_INIT_FILE))); eval(readFileContent(br)); } /** * @see org.ow2.proactive.utils.console.ConsoleModel#startModel() */ public void startModel() throws Exception { checkIsReady(); console.start(" > "); console.print("Type command here (type '?' or help() to see the list of commands)\n"); initialize(); String stmt; while (!terminated) { stmt = console.readStatement(); if ("?".equals(stmt)) { console.print("\n" + helpScreen()); } else { eval(stmt); console.print(""); } } console.stop(); } /** * Return the logsNbLines last lines of the given file. * * @param fileName the file to be displayed * @return the N last lines of the given file */ private static String readLastNLines(String fileName) { StringBuilder toret = new StringBuilder(); File f = new File(logsDirectory + File.separator + fileName); try { RandomAccessFile raf = new RandomAccessFile(f, "r"); long cursor = raf.length() - 2; int nbLines = logsNbLines; byte b; raf.seek(cursor); while (nbLines > 0) { if ((b = raf.readByte()) == '\n') { nbLines } cursor raf.seek(cursor); if (nbLines > 0) { toret.insert(0, (char) b); } } } catch (Exception e) { } return toret.toString(); } public static void exit() { getModel().checkIsReady(); getModel().exit_(); } private void exit_() { if (allowExitCommand) { console.print("Exiting controller."); try { rm.disconnect(); } catch (Exception e) { } terminated = true; } else { console.print("Exit command has been disabled !"); } } public static RMAdmin getAdminRM() { getModel().checkIsReady(); return getModel().getAdminRM_(); } private RMAdmin getAdminRM_() { return rm; } /** * Connect the Resource manager value to the given rm value * * @param rm the Resource manager to connect */ public void connectRM(RMAdmin rm) { if (rm == null) { throw new NullPointerException("Given Resource Manager is null"); } this.rm = rm; } /** * Set the JMX information : it is not a mandatory option, if set, it will show informations, if not nothing will be displayed. * * @param info the jmx information about the current connection */ public void setJMXInfo(MBeanInfoViewer info) { jmxInfoViewer = info; } public static void listInfrastructures() { getModel().checkIsReady(); getModel().print("Available node source infrastructures:"); for (PluginDescriptor plugin : getModel().rm.getSupportedNodeSourceInfrastructures()) { getModel().print(plugin.toString()); } } public static void listPolicies() { getModel().checkIsReady(); getModel().print("Available node source policies:"); for (PluginDescriptor plugin : getModel().rm.getSupportedNodeSourcePolicies()) { getModel().print(plugin.toString()); } } }
package edu.iastate.music.marching.attendance.test.unit.controllers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import org.junit.Test; import edu.iastate.music.marching.attendance.controllers.AbsenceController; import edu.iastate.music.marching.attendance.controllers.DataTrain; import edu.iastate.music.marching.attendance.controllers.EventController; import edu.iastate.music.marching.attendance.controllers.FormController; import edu.iastate.music.marching.attendance.controllers.UserController; import edu.iastate.music.marching.attendance.model.Absence; import edu.iastate.music.marching.attendance.model.Event; import edu.iastate.music.marching.attendance.model.Form; import edu.iastate.music.marching.attendance.model.User; import edu.iastate.music.marching.attendance.test.AbstractTest; import edu.iastate.music.marching.attendance.test.util.Users; @SuppressWarnings("deprecation") public class AbsenceControllerTest extends AbstractTest { @Test public void testCreateAbsence() { /* * Test to see if adding an absence actually works */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0400"); Date eventEnd = makeDate("2012-06-16 0600"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(eventStart)); assertTrue(absence.getEnd().equals(eventEnd)); assertTrue(absence.getType() == Absence.Type.Absence); } @Test(expected = IllegalArgumentException.class) public void testCreateAbsenceFail() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0400"); Date eventEnd = makeDate("2012-06-16 0300"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); } @Test public void testAbsenceVsAbsenceSameTime() { /* * When we have two absences at the same time only one of them should be * added */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date contesterStart = makeDate("2012-06-16 0500"); Date contesterEnd = makeDate("2012-06-16 0700"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, contesterStart, contesterEnd); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(eventStart)); assertTrue(absence.getEnd().equals(eventEnd)); assertTrue(absence.getType() == Absence.Type.Absence); } @Test public void testAbsenceVsAbsenceDiffTime() { /* * When we have two absences at different times for different events * they should both remain */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date contesterStart = makeDate("2012-06-16 0800"); Date contesterEnd = makeDate("2012-06-16 0900"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getEventController().createOrUpdate(Event.Type.Performance, contesterStart, contesterEnd); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, contesterStart, contesterEnd); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(2, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(eventStart) || absence.getStart().equals(contesterStart)); assertTrue(absence.getEnd().equals(eventEnd) || absence.getEnd().equals(contesterEnd)); assertTrue(absence.getType() == Absence.Type.Absence); absence = studentAbsences.get(1); assertTrue(absence.getStart().equals(eventStart) || absence.getStart().equals(contesterStart)); assertTrue(absence.getEnd().equals(eventEnd) || absence.getEnd().equals(contesterEnd)); assertTrue(absence.getType() == Absence.Type.Absence); } @Test public void testAbsenceVsTardySameEvent() { /* * If we have an absence and a tardy added where the tardy happens * during the absence, the absence should be removed and the tardy * should remain. This test adds the absence first and the tardy second */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardy = makeDate("2012-06-16 0515"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); train.getAbsenceController().createOrUpdateTardy(student, tardy); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(tardy)); assertTrue(absence.getType() == Absence.Type.Tardy); } @Test public void testAbsenceVsTardyDiffEvent() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date event1Start = makeDate("2012-06-16 0500"); Date event1End = makeDate("2012-06-16 0700"); Date event2Start = makeDate("2012-07-16 0500"); Date event2End = makeDate("2012-07-16 0700"); Date tardyDate = makeDate("2012-07-16 0515"); train.getEventController().createOrUpdate(Event.Type.Performance, event1Start, event1End); train.getEventController().createOrUpdate(Event.Type.Performance, event2Start, event2End); train.getAbsenceController().createOrUpdateAbsence(student, event1Start, event1End); train.getAbsenceController().createOrUpdateTardy(student, tardyDate); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(2, studentAbsences.size()); Absence absence = (studentAbsences.get(0).getType() == Absence.Type.Absence) ? studentAbsences .get(0) : studentAbsences.get(1); Absence tardy = (studentAbsences.get(0).getType() == Absence.Type.Tardy) ? studentAbsences .get(0) : studentAbsences.get(1); assertTrue(absence.getStart().equals(event1Start)); assertTrue(absence.getEnd().equals(event1End)); assertTrue(tardy.getStart().equals(tardyDate)); } @Test public void testAbsenceVsEarlySameEvent() { /* * If we have an absence and an early checkout added during the same * interval, the absence should be removed and the early checkout should * remain */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date early = makeDate("2012-06-16 0515"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); train.getAbsenceController() .createOrUpdateEarlyCheckout(student, early); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(early)); assertTrue(absence.getType() == Absence.Type.EarlyCheckOut); } @Test public void testAbsenceVsEarlyDiffEvent() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date event1Start = makeDate("2012-06-16 0500"); Date event1End = makeDate("2012-06-16 0700"); Date event2Start = makeDate("2012-07-16 0500"); Date event2End = makeDate("2012-07-16 0700"); Date earlyDate = makeDate("2012-07-16 0515"); train.getEventController().createOrUpdate(Event.Type.Performance, event1Start, event1End); train.getEventController().createOrUpdate(Event.Type.Performance, event2Start, event2End); train.getAbsenceController().createOrUpdateAbsence(student, event1Start, event1End); train.getAbsenceController().createOrUpdateEarlyCheckout(student, earlyDate); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(2, studentAbsences.size()); Absence absence = (studentAbsences.get(0).getType() == Absence.Type.Absence) ? studentAbsences .get(0) : studentAbsences.get(1); Absence early = (studentAbsences.get(0).getType() == Absence.Type.EarlyCheckOut) ? studentAbsences .get(0) : studentAbsences.get(1); assertTrue(absence.getStart().equals(event1Start)); assertTrue(absence.getEnd().equals(event1End)); assertTrue(early.getStart().equals(earlyDate)); } @Test public void testTardyVsAbsence() { /* * This test is the same idea as the testAbsenceVsTardy method only it * adds the tardy first */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardy = makeDate("2012-06-16 0515"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController().createOrUpdateTardy(student, tardy); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(tardy)); assertTrue(absence.getType() == Absence.Type.Tardy); } @Test public void testTardyVsTardySameEvent() { /* * If we have two tardies added for the same event we need to take the * later tardy. This method checks adding the earlier tardy before the * later tardy and vice versa */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student1 = Users.createStudent(uc, "student1", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student2 = Users.createStudent(uc, "student2", "123456782", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardy = makeDate("2012-06-16 0515"); Date tardyLate = makeDate("2012-06-16 0520"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); // Adding the early tardy before the late tardy train.getAbsenceController().createOrUpdateTardy(student1, tardy); train.getAbsenceController().createOrUpdateTardy(student1, tardyLate); List<Absence> studentAbsences = train.getAbsenceController().get(student1); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(tardyLate)); assertTrue(absence.getType() == Absence.Type.Tardy); // Adding the late tardy before the early tardy train.getAbsenceController().createOrUpdateTardy(student2, tardyLate); train.getAbsenceController().createOrUpdateTardy(student2, tardy); List<Absence> student2Absences = train.getAbsenceController().get(student2); assertEquals(1, studentAbsences.size()); Absence absence2 = student2Absences.get(0); assertTrue(absence2.getStart().equals(tardyLate)); assertTrue(absence2.getType() == Absence.Type.Tardy); } @Test public void testTardyVsTardyDiffEvent() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student1 = Users.createStudent(uc, "student1", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date event1Start = makeDate("2012-06-16 0500"); Date event1End = makeDate("2012-06-16 0700"); Date event2Start = makeDate("2012-06-16 0800"); Date event2End = makeDate("2012-06-16 0900"); Date tardy = makeDate("2012-06-16 0515"); Date otherTardy = makeDate("2012-06-16 0820"); train.getEventController().createOrUpdate(Event.Type.Performance, event1Start, event1End); train.getEventController().createOrUpdate(Event.Type.Performance, event2Start, event2End); train.getAbsenceController().createOrUpdateTardy(student1, tardy); train.getAbsenceController().createOrUpdateTardy(student1, otherTardy); List<Absence> studentAbsences = train.getAbsenceController().get(student1); assertEquals(2, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(tardy) || absence.getStart().equals(otherTardy)); assertTrue(absence.getType() == Absence.Type.Tardy); absence = studentAbsences.get(1); assertTrue(absence.getStart().equals(tardy) || absence.getStart().equals(otherTardy)); assertTrue(absence.getType() == Absence.Type.Tardy); } @Test public void testTardyVsEarly() { /* * This method tests these four cases: Case 1: don't overlap, both * should remain. a: Adding Tardy first b: Adding EarlyCheckout first * * Case 2: do overlap, become an absence a: Adding Tardy first b: Adding * EarlyCheckout first */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User nonOverTardyFirst = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); User nonOverEarlyFirst = Users.createStudent(uc, "student2", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User overlapTardyFirst = Users.createStudent(uc, "student3", "123456781", "First", "last", 2, "major", User.Section.AltoSax); User overlapEarlyFirst = Users.createStudent(uc, "student4", "123456782", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardyDate = makeDate("2012-06-16 0515"); Date earlyNon = makeDate("2012-06-16 0650"); Date earlyOverlap = makeDate("2012-06-16 0510"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); // Case 1.a train.getAbsenceController().createOrUpdateTardy(nonOverTardyFirst, tardyDate); train.getAbsenceController().createOrUpdateEarlyCheckout( nonOverTardyFirst, earlyNon); List<Absence> nonOverTardyFirstAbsences = train.getAbsenceController() .get(nonOverTardyFirst); assertEquals(2, nonOverTardyFirstAbsences.size()); Absence tardy = (nonOverTardyFirstAbsences.get(0).getType() == Absence.Type.Tardy) ? nonOverTardyFirstAbsences .get(0) : nonOverTardyFirstAbsences.get(1); Absence earlyCheckOut = (nonOverTardyFirstAbsences.get(0).getType() == Absence.Type.EarlyCheckOut) ? nonOverTardyFirstAbsences .get(0) : nonOverTardyFirstAbsences.get(1); assertTrue(tardy.getType() == Absence.Type.Tardy); assertTrue(tardy.getStart().equals(tardyDate)); assertTrue(earlyCheckOut.getType() == Absence.Type.EarlyCheckOut); assertTrue(earlyCheckOut.getStart().equals(earlyNon)); // Case 1.b train.getAbsenceController().createOrUpdateEarlyCheckout( nonOverEarlyFirst, earlyNon); train.getAbsenceController().createOrUpdateTardy(nonOverEarlyFirst, tardyDate); List<Absence> nonOverEarlyFirstAbsences = train.getAbsenceController().get(nonOverEarlyFirst); assertEquals(2, nonOverEarlyFirstAbsences.size()); tardy = (nonOverEarlyFirstAbsences.get(0).getType() == Absence.Type.Tardy) ? nonOverEarlyFirstAbsences .get(0) : nonOverEarlyFirstAbsences.get(1); earlyCheckOut = (nonOverEarlyFirstAbsences.get(0).getType() == Absence.Type.EarlyCheckOut) ? nonOverEarlyFirstAbsences .get(0) : nonOverEarlyFirstAbsences.get(1); assertTrue(tardy.getType() == Absence.Type.Tardy); assertTrue(tardy.getStart().equals(tardyDate)); assertTrue(earlyCheckOut.getType() == Absence.Type.EarlyCheckOut); assertTrue(earlyCheckOut.getStart().equals(earlyNon)); // Case 2.a train.getAbsenceController().createOrUpdateTardy(overlapTardyFirst, tardyDate); train.getAbsenceController().createOrUpdateEarlyCheckout(overlapTardyFirst, earlyOverlap); List<Absence> overlapTardyFirstAbsences = train.getAbsenceController().get(overlapTardyFirst); assertEquals(1, overlapTardyFirstAbsences.size()); Absence createdAbsence = overlapTardyFirstAbsences.get(0); assertTrue(createdAbsence.getType() == Absence.Type.Absence); assertEquals(eventStart, createdAbsence.getStart()); assertEquals(eventEnd, createdAbsence.getEnd()); // Case 2.b train.getAbsenceController().createOrUpdateEarlyCheckout(overlapEarlyFirst, earlyOverlap); train.getAbsenceController().createOrUpdateTardy(overlapEarlyFirst, tardyDate); List<Absence> overlapEarlyFirstAbsences = train.getAbsenceController().get(overlapEarlyFirst); assertEquals(1, overlapEarlyFirstAbsences.size()); createdAbsence = overlapEarlyFirstAbsences.get(0); assertTrue(createdAbsence.getType() == Absence.Type.Absence); assertEquals(eventStart, createdAbsence.getStart()); assertEquals(eventEnd, createdAbsence.getEnd()); } @Test public void testEarlyVsAbsence() { /* * Same as the testAbsenceVsEarly method only this adds the Early * checkout before the absence */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date early = makeDate("2012-06-16 0515"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); train.getAbsenceController() .createOrUpdateEarlyCheckout(student, early); train.getAbsenceController().createOrUpdateAbsence(student, eventStart, eventEnd); List<Absence> studentAbsences = train.getAbsenceController().get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(early)); assertTrue(absence.getType() == Absence.Type.EarlyCheckOut); } @Test public void testEarlyVsEarlySameEvent() { /* * If we have two early checkouts added for the same time zone we need * to take the earlier of the two and remove the later. This method * checks adding the later checkout before the earlier checkout and vice * versa */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student1 = Users.createStudent(uc, "student1", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student2 = Users.createStudent(uc, "student2", "123456780", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date early = makeDate("2012-06-16 0550"); Date earlyEarlier = makeDate("2012-06-16 0545"); train.getEventController().createOrUpdate(Event.Type.Performance, eventStart, eventEnd); // Adding the early checkout before the earlier checkout train.getAbsenceController().createOrUpdateEarlyCheckout(student1, early); train.getAbsenceController().createOrUpdateEarlyCheckout(student1, earlyEarlier); List<Absence> studentAbsences = train.getAbsenceController().get( student1); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(earlyEarlier)); assertTrue(absence.getType() == Absence.Type.EarlyCheckOut); // Adding the earlier early before the early train.getAbsenceController().createOrUpdateEarlyCheckout(student2, earlyEarlier); train.getAbsenceController().createOrUpdateEarlyCheckout(student2, early); List<Absence> student2Absences = train.getAbsenceController().get( student2); assertEquals(1, studentAbsences.size()); Absence absence2 = student2Absences.get(0); assertTrue(absence2.getStart().equals(earlyEarlier)); assertTrue(absence2.getType() == Absence.Type.EarlyCheckOut); } @Test public void testEarlyVsEarlyDiffEvent() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student1 = Users.createStudent(uc, "student1", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date event1Start = makeDate("2012-06-16 0500"); Date event1End = makeDate("2012-06-16 0700"); Date event2Start = makeDate("2012-06-16 0800"); Date event2End = makeDate("2012-06-16 0900"); Date early = makeDate("2012-06-16 0550"); Date otherEarly = makeDate("2012-06-16 0845"); train.getEventController().createOrUpdate(Event.Type.Performance, event1Start, event1End); train.getEventController().createOrUpdate(Event.Type.Performance, event2Start, event2End); train.getAbsenceController().createOrUpdateEarlyCheckout(student1, early); train.getAbsenceController().createOrUpdateEarlyCheckout(student1, otherEarly); List<Absence> studentAbsences = train.getAbsenceController().get( student1); assertEquals(2, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(early) || absence.getStart().equals(otherEarly)); assertTrue(absence.getType() == Absence.Type.EarlyCheckOut); absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(early) || absence.getStart().equals(otherEarly)); assertTrue(absence.getType() == Absence.Type.EarlyCheckOut); } @Test public void testApproveAbsence() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "student1", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date start = makeDate("2012-06-16 0500"); Date end = makeDate("2012-06-16 0700"); train.getEventController().createOrUpdate(Event.Type.Performance, start, end); Absence abs = train.getAbsenceController().createOrUpdateAbsence(student, start, end); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); List<Absence> studentAbs = train.getAbsenceController().get(student); assertEquals(1, studentAbs.size()); Absence absence = studentAbs.get(0); assertTrue(absence.getStart().equals(start)); assertTrue(absence.getEnd().equals(end)); assertTrue(absence.getType() == Absence.Type.Absence); assertTrue(absence.getStatus() == Absence.Status.Approved); } @Test public void testApprovedAbsenceDominatesAbsence() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "student", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student1 = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); Date start = makeDate("2012-06-16 0500"); Date end = makeDate("2012-06-16 0600"); //Approved saved first train.getEventController().createOrUpdate(Event.Type.Performance, start, end); Absence abs = train.getAbsenceController().createOrUpdateAbsence(student, start, end); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); train.getAbsenceController().createOrUpdateAbsence(student, start, end); List<Absence> studentAbs = train.getAbsenceController().get(student); assertEquals(1, studentAbs.size()); Absence absence = studentAbs.get(0); assertTrue(absence.getStart().equals(start)); assertTrue(absence.getEnd().equals(end)); assertTrue(absence.getType() == Absence.Type.Absence); assertTrue(absence.getStatus() == Absence.Status.Approved); } @Test public void testApprovedAbsenceDominatesTardy() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "student", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student1 = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); Date start = makeDate("2012-06-16 0500"); Date tardyStart = makeDate("2012-06-16 0515"); Date end = makeDate("2012-06-16 0600"); //Approved saved first train.getEventController().createOrUpdate(Event.Type.Performance, start, end); Absence abs = train.getAbsenceController().createOrUpdateAbsence(student, start, end); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); train.getAbsenceController().createOrUpdateTardy(student, tardyStart); List<Absence> studentAbs = train.getAbsenceController().get(student); assertEquals(1, studentAbs.size()); Absence absence = studentAbs.get(0); assertTrue(absence.getStart().equals(start)); assertTrue(absence.getEnd().equals(end)); assertTrue(absence.getType() == Absence.Type.Absence); assertTrue(absence.getStatus() == Absence.Status.Approved); } @Test public void testApprovedAbsenceDominatesEarly() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "student", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student1 = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); Date start = makeDate("2012-06-16 0500"); Date tardyStart = makeDate("2012-06-16 0515"); Date end = makeDate("2012-06-16 0600"); //Approved saved first train.getEventController().createOrUpdate(Event.Type.Performance, start, end); Absence abs = train.getAbsenceController().createOrUpdateAbsence(student, start, end); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); train.getAbsenceController().createOrUpdateEarlyCheckout(student, tardyStart); List<Absence> studentAbs = train.getAbsenceController().get(student); assertEquals(1, studentAbs.size()); Absence absence = studentAbs.get(0); assertTrue(absence.getStart().equals(start)); assertTrue(absence.getEnd().equals(end)); assertTrue(absence.getType() == Absence.Type.Absence); assertTrue(absence.getStatus() == Absence.Status.Approved); } @Test public void testApprovedTardyVsAbsence() { /* * This test is the same idea as the testAbsenceVsTardy method only it * adds the tardy first */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); EventController ec = train.getEventController(); AbsenceController ac = train.getAbsenceController(); User student = Users.createStudent(uc, "studenttt", "123456789", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardyDate = makeDate("2012-06-16 0515"); ec.createOrUpdate(Event.Type.Performance, eventStart, eventEnd); Absence tardy = ac.createOrUpdateTardy(student, tardyDate); tardy.setStatus(Absence.Status.Approved); ac.updateAbsence(tardy); ac.createOrUpdateAbsence(student, eventStart, eventEnd); List<Absence> studentAbsences = ac.get( student); assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(tardyDate)); assertTrue(absence.getType() == Absence.Type.Tardy); assertTrue(absence.getStatus() == Absence.Status.Approved); } @Test public void testApprovedTardyDominatesTardySameTime() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "student", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student1 = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); Date start = makeDate("2012-06-16 0500"); Date end = makeDate("2012-06-16 0600"); //Approved saved first train.getEventController().createOrUpdate(Event.Type.Performance, start, end); Absence abs = train.getAbsenceController().createOrUpdateTardy(student, start); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); train.getAbsenceController().createOrUpdateTardy(student, start); List<Absence> studentAbs = train.getAbsenceController().get(student); assertEquals(1, studentAbs.size()); Absence absence = studentAbs.get(0); assertTrue(absence.getStart().equals(start)); assertTrue(absence.getType() == Absence.Type.Tardy); assertTrue(absence.getStatus() == Absence.Status.Approved); //Approved saved second train.getAbsenceController().createOrUpdateTardy(student1, start); abs = train.getAbsenceController().createOrUpdateTardy(student1, start); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); studentAbs = train.getAbsenceController().get(student1); assertEquals(1, studentAbs.size()); absence = studentAbs.get(0); assertTrue(absence.getStart().equals(start)); assertTrue(absence.getType() == Absence.Type.Tardy); assertTrue(absence.getStatus() == Absence.Status.Approved); } @Test public void testApprovedTardyDominatesTardyDiffTime() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); EventController ec = train.getEventController(); AbsenceController ac = train.getAbsenceController(); User student1 = Users.createStudent(uc, "student1", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student2 = Users.createStudent(uc, "student2", "123456782", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardy = makeDate("2012-06-16 0515"); Date tardyLate = makeDate("2012-06-16 0520"); ec.createOrUpdate(Event.Type.Performance, eventStart, eventEnd); //Approving the early tardy Absence t = ac.createOrUpdateTardy(student1, tardy); t.setStatus(Absence.Status.Approved); ac.updateAbsence(t); ac.createOrUpdateTardy(student1, tardyLate); List<Absence> studentAbsences = ac.get(student1); //Should be the approved tardy values assertEquals(1, studentAbsences.size()); Absence absence = studentAbsences.get(0); assertTrue(absence.getStart().equals(tardy)); assertTrue(absence.getStatus() == Absence.Status.Approved); assertTrue(absence.getType() == Absence.Type.Tardy); // Approving the later tardy t = ac.createOrUpdateTardy(student2, tardyLate); t.setStatus(Absence.Status.Approved); ac.updateAbsence(t); ac.createOrUpdateTardy(student2, tardy); List<Absence> student2Absences = ac.get(student2); //Should still be the approved values assertEquals(1, student2Absences.size()); Absence absence2 = student2Absences.get(0); assertTrue(absence2.getStart().equals(tardyLate)); assertTrue(absence2.getStatus() == Absence.Status.Approved); assertTrue(absence2.getType() == Absence.Type.Tardy); } @Test public void testApprovedTardyVsEarly() { /* * This method tests these four cases: * Case 1: don't overlap, both should remain. * a: Adding Tardy first * b: Adding EarlyCheckout first * * Case 2: do overlap, become an absence * a: Adding Tardy first * b: Adding EarlyCheckout first */ DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); EventController ec = train.getEventController(); AbsenceController ac = train.getAbsenceController(); User nonOverTardyFirst = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); User nonOverEarlyFirst = Users.createStudent(uc, "student2", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User overlapTardyFirst = Users.createStudent(uc, "student3", "123456781", "First", "last", 2, "major", User.Section.AltoSax); User overlapEarlyFirst = Users.createStudent(uc, "student4", "123456782", "First", "last", 2, "major", User.Section.AltoSax); Date eventStart = makeDate("2012-06-16 0500"); Date eventEnd = makeDate("2012-06-16 0700"); Date tardyDate = makeDate("2012-06-16 0515"); Date earlyNon = makeDate("2012-06-16 0650"); Date earlyOverlap = makeDate("2012-06-16 0510"); ec.createOrUpdate(Event.Type.Performance, eventStart, eventEnd); // Case 1.a Absence t = ac.createOrUpdateTardy(nonOverTardyFirst, tardyDate); t.setStatus(Absence.Status.Approved); ac.updateAbsence(t); ac.createOrUpdateEarlyCheckout(nonOverTardyFirst, earlyNon); List<Absence> nonOverTardyFirstAbsences = ac.get(nonOverTardyFirst); assertEquals(2, nonOverTardyFirstAbsences.size()); Absence tardy = (nonOverTardyFirstAbsences.get(0).getType() == Absence.Type.Tardy) ? nonOverTardyFirstAbsences .get(0) : nonOverTardyFirstAbsences.get(1); Absence earlyCheckOut = (nonOverTardyFirstAbsences.get(0).getType() == Absence.Type.EarlyCheckOut) ? nonOverTardyFirstAbsences .get(0) : nonOverTardyFirstAbsences.get(1); assertTrue(tardy.getType() == Absence.Type.Tardy); assertTrue(tardy.getStatus() == Absence.Status.Approved); assertTrue(tardy.getStart().equals(tardyDate)); assertTrue(earlyCheckOut.getType() == Absence.Type.EarlyCheckOut); assertTrue(earlyCheckOut.getStatus() == Absence.Status.Pending); assertTrue(earlyCheckOut.getStart().equals(earlyNon)); // Case 1.b ac.createOrUpdateEarlyCheckout(nonOverEarlyFirst, earlyNon); t = ac.createOrUpdateTardy(nonOverEarlyFirst, tardyDate); t.setStatus(Absence.Status.Approved); ac.updateAbsence(t); List<Absence> nonOverEarlyFirstAbsences = train.getAbsenceController() .get(nonOverEarlyFirst); assertEquals(2, nonOverEarlyFirstAbsences.size()); tardy = (nonOverEarlyFirstAbsences.get(0).getType() == Absence.Type.Tardy) ? nonOverEarlyFirstAbsences .get(0) : nonOverEarlyFirstAbsences.get(1); earlyCheckOut = (nonOverEarlyFirstAbsences.get(0).getType() == Absence.Type.EarlyCheckOut) ? nonOverEarlyFirstAbsences .get(0) : nonOverEarlyFirstAbsences.get(1); assertTrue(tardy.getType() == Absence.Type.Tardy); assertTrue(tardy.getStatus() == Absence.Status.Approved); assertTrue(tardy.getStart().equals(tardyDate)); assertTrue(earlyCheckOut.getType() == Absence.Type.EarlyCheckOut); assertTrue(earlyCheckOut.getStatus() == Absence.Status.Pending); assertTrue(earlyCheckOut.getStart().equals(earlyNon)); // Case 2.a t = ac.createOrUpdateTardy(overlapTardyFirst, tardyDate); t.setStatus(Absence.Status.Approved); ac.updateAbsence(t); ac.createOrUpdateEarlyCheckout(overlapTardyFirst, earlyOverlap); List<Absence> overlapTardyFirstAbsences = train.getAbsenceController().get(overlapTardyFirst); assertEquals(1, overlapTardyFirstAbsences.size()); Absence createdAbsence = overlapTardyFirstAbsences.get(0); assertTrue(createdAbsence.getType() == Absence.Type.Absence); assertTrue(createdAbsence.getStatus() == Absence.Status.Pending); assertEquals(eventStart, createdAbsence.getStart()); assertEquals(eventEnd, createdAbsence.getEnd()); // Case 2.b ac.createOrUpdateEarlyCheckout(overlapEarlyFirst, earlyOverlap); ac.createOrUpdateTardy(overlapEarlyFirst, tardyDate); List<Absence> overlapEarlyFirstAbsences = train.getAbsenceController().get(overlapEarlyFirst); assertEquals(1, overlapEarlyFirstAbsences.size()); createdAbsence = overlapEarlyFirstAbsences.get(0); assertTrue(createdAbsence.getType() == Absence.Type.Absence); assertTrue(createdAbsence.getStatus() == Absence.Status.Pending); assertEquals(eventStart, createdAbsence.getStart()); assertEquals(eventEnd, createdAbsence.getEnd()); } @Test public void testApprovedEarlyDominatesEarly() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); User student = Users.createStudent(uc, "student", "123456789", "First", "last", 2, "major", User.Section.AltoSax); User student1 = Users.createStudent(uc, "student1", "123456780", "First", "last", 2, "major", User.Section.AltoSax); Date start = makeDate("2012-06-16 0500"); Date checkout = makeDate("2012-06-16 0550"); Date end = makeDate("2012-06-16 0600"); //Approved saved first train.getEventController().createOrUpdate(Event.Type.Performance, start, end); Absence abs = train.getAbsenceController().createOrUpdateEarlyCheckout(student, checkout); abs.setStatus(Absence.Status.Approved); train.getAbsenceController().updateAbsence(abs); train.getAbsenceController().createOrUpdateEarlyCheckout(student, checkout); List<Absence> studentAbs = train.getAbsenceController().get(student); assertEquals(1, studentAbs.size()); Absence absence = studentAbs.get(0); assertTrue(absence.getStart().equals(checkout)); assertTrue(absence.getType() == Absence.Type.EarlyCheckOut); assertTrue(absence.getStatus() == Absence.Status.Approved); } private Date makeDate(String sDate) { // Private method to make dates out of strings following the format I // always use try { return new SimpleDateFormat("yyyy-MM-dd HHmm").parse(sDate); } catch (ParseException e) { e.printStackTrace(); return null; } } /** * Add a form A, approve it, add an absence, check that it is approved. */ @Test public void testAutoApproveWithFormA() { DataTrain train = getDataTrain(); UserController uc = train.getUsersController(); EventController ec = train.getEventController(); AbsenceController ac = train.getAbsenceController(); FormController fc = train.getFormsController(); User student = Users.createStudent(uc, "student1", "123456789", "John", "Cox", 2, "major", User.Section.AltoSax); Calendar date = Calendar.getInstance(); date.set(2012, 7, 7, 0, 0, 0); Calendar start = Calendar.getInstance(); start.set(2012, 7, 7, 16, 30, 0); Calendar end = Calendar.getInstance(); end.set(2012, 7, 7, 17, 50, 0); Form form = fc.createFormA(student, date.getTime(), "I love band."); form.setStatus(Form.Status.Approved); fc.update(form); Event e = ec.createOrUpdate(Event.Type.Performance, start.getTime(), end.getTime()); Absence a = ac.createOrUpdateAbsence(student, e); assertEquals(Absence.Status.Approved, a.getStatus()); } }
package uk.co.jemos.podam.test.unit.features.typeManufacturing; import net.serenitybdd.junit.runners.SerenityRunner; import net.thucydides.core.annotations.Title; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import uk.co.jemos.podam.api.AttributeMetadata; import uk.co.jemos.podam.api.DataProviderStrategy; import uk.co.jemos.podam.common.PodamConstants; import uk.co.jemos.podam.test.dto.ClassGenericConstructorPojo; import uk.co.jemos.podam.test.dto.SimplePojoToTestSetters; import uk.co.jemos.podam.test.enums.ExternalRatePodamEnum; import uk.co.jemos.podam.test.unit.AbstractPodamSteps; import uk.co.jemos.podam.typeManufacturers.TypeManufacturerParamsWrapper; import uk.co.jemos.podam.typeManufacturers.TypeManufacturerParamsWrapperForGenericTypes; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; @RunWith(SerenityRunner.class) public class TypeManufacturingTest extends AbstractPodamSteps { /** The application logger */ private static final Logger LOG = LogManager.getLogger(TypeManufacturingTest.class); @Test @Title("Podam Messaging System should return an int primitive value") public void podamMessagingSystemShouldReturnAnIntValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> intMessage = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, int.class); podamValidationSteps.theObjectShouldNotBeNull(intMessage); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, intMessage); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theIntFieldShouldNotBeZero((Integer) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return an integer value") public void podamMessagingSystemShouldReturnAnIntegerValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> intMessage = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Integer.class); podamValidationSteps.theObjectShouldNotBeNull(intMessage); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, intMessage); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theIntFieldShouldNotBeZero((Integer) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a boolean primitive value") public void podamMessagingSystemShouldReturnABooleanPrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, boolean.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theBooleanValueIsTrue((Boolean) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a boolean wrapped value") public void podamMessagingSystemShouldReturnABooleanWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Boolean.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theBooleanValueIsTrue((Boolean) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a char primitive value") public void podamMessagingSystemShouldReturnACharacterPrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, char.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Character) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Character wrapped value") public void podamMessagingSystemShouldReturnACharacterWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Character.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Character) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a short primitive value") public void podamMessagingSystemShouldReturnAShortPrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, short.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Short) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Short wrapped value") public void podamMessagingSystemShouldReturnAShortWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Short.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Short) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a byte primitive value") public void podamMessagingSystemShouldReturnABytePrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, byte.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Byte) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Byte wrapped value") public void podamMessagingSystemShouldReturnAByteWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Byte.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Byte) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a long primitive value") public void podamMessagingSystemShouldReturnALongPrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, long.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Long) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Long wrapped value") public void podamMessagingSystemShouldReturnALongWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Long.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Long) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a float primitive value") public void podamMessagingSystemShouldReturnAFloatPrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, float.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Float) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Float wrapped value") public void podamMessagingSystemShouldReturnAFloatWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Float.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Float) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a double primitive value") public void podamMessagingSystemShouldReturnADoublePrimitiveValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, double.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Double) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Double wrapped value") public void podamMessagingSystemShouldReturnADoubleWrappedValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, Double.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((Double) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a String value") public void podamMessagingSystemShouldReturnAStringValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnEmptyAttributeMetadata (SimplePojoToTestSetters.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessage( paramsWrapper, PodamConstants.HEADER_NAME, String.class); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull((String) value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return an Enum value") public void podamMessagingSystemShouldReturnAnEnumValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnAttributeMetadataForEnums (ExternalRatePodamEnum.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); TypeManufacturerParamsWrapper paramsWrapper = new TypeManufacturerParamsWrapper(dataProviderStrategy, attributeMetadata); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessageWithStringQualifier( paramsWrapper, PodamConstants.HEADER_NAME, PodamConstants.ENUMERATION_QUALIFIER); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); podamValidationSteps.theObjectShouldNotBeNull(value.getPayload()); } finally { if (null != applicationContext) { applicationContext.close(); } } } @Test @Title("Podam Messaging System should return a Generic Type value") public void podamMessagingSystemShouldReturnAGenericTypeValue() throws Exception { DataProviderStrategy dataProviderStrategy = podamFactorySteps.givenARandomDataProviderStrategy(); AbstractApplicationContext applicationContext = podamFactorySteps.givenPodamRootApplicationContext(); podamValidationSteps.theObjectShouldNotBeNull(applicationContext); try { MessageChannel inputChannel = podamFactorySteps.givenAMessageChannelToManufactureValues(applicationContext); podamValidationSteps.theObjectShouldNotBeNull(inputChannel); AttributeMetadata attributeMetadata = podamFactorySteps.givenAnAttributeMetadataForGenericTypes (ClassGenericConstructorPojo.class); podamValidationSteps.theObjectShouldNotBeNull(attributeMetadata); Map<String, Type> genericTypeArgumentsMap = new HashMap<String, Type>(); genericTypeArgumentsMap.put("T", String.class); TypeManufacturerParamsWrapperForGenericTypes paramsWrapper = new TypeManufacturerParamsWrapperForGenericTypes(dataProviderStrategy, attributeMetadata, genericTypeArgumentsMap, String.class); Message<? extends Object> message = podamFactorySteps.givenATypeManufacturingMessageWithStringQualifier( paramsWrapper, PodamConstants.HEADER_NAME, PodamConstants.GENERIC_TYPE_QUALIFIER); podamValidationSteps.theObjectShouldNotBeNull(message); Message value = podamInvocationSteps.whenISendAMessageToTheChannel(inputChannel, message); podamValidationSteps.theObjectShouldNotBeNull(value); Object payload = value.getPayload(); podamValidationSteps.theObjectShouldNotBeNull(payload); podamValidationSteps.theTwoObjectsShouldBeEqual(String.class, payload); } finally { if (null != applicationContext) { applicationContext.close(); } } } }
package com.systematic.trading.analysis; import java.math.MathContext; import java.time.LocalDate; import java.time.Period; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.systematic.trading.analysis.model.ProcessLongBuySignals; import com.systematic.trading.analysis.view.DisplayBuySignals; import com.systematic.trading.data.DataService; import com.systematic.trading.data.DataServiceUpdater; import com.systematic.trading.data.DataServiceUpdaterImpl; import com.systematic.trading.data.HibernateDataService; import com.systematic.trading.data.TradingDayPrices; import com.systematic.trading.data.util.HibernateUtil; import com.systematic.trading.signals.indicator.IndicatorSignalGenerator; import com.systematic.trading.signals.indicator.MovingAveragingConvergeDivergenceSignals; import com.systematic.trading.signals.indicator.SimpleMovingAverageGradientSignals; import com.systematic.trading.signals.indicator.SimpleMovingAverageGradientSignals.GradientType; import com.systematic.trading.signals.model.BuySignal; import com.systematic.trading.signals.model.IndicatorSignalType; import com.systematic.trading.signals.model.filter.IndicatorsOnSameDaySignalFilter; import com.systematic.trading.signals.model.filter.SignalFilter; import com.systematic.trading.signals.model.filter.RollingTimePeriodSignalFilterDecorator; public class TodaysBuySignals { private static final MathContext MATH_CONTEXT = MathContext.DECIMAL64; private static final Logger LOG = LogManager.getLogger( TodaysBuySignals.class ); /** The oldest signal date (inclusive) from today to report, includes non-trading days. */ private static final int OLDEST_SIGNAL = 6; /* Days data needed - 20 + 20 for the MACD part EMA(20), Weekend and bank holidays */ private static final int HISTORY_REQUIRED = 50 + 16 + 5; public static void main( final String... args ) { updateEquities(); final LocalDate endDate = LocalDate.now(); final LocalDate startDate = endDate.minus( HISTORY_REQUIRED, ChronoUnit.DAYS ); final MovingAveragingConvergeDivergenceSignals macd = new MovingAveragingConvergeDivergenceSignals( 10, 20, 7, MATH_CONTEXT ); final int smaLookback = 50; final int daysOfSmaGradient = 7; final SimpleMovingAverageGradientSignals sma = new SimpleMovingAverageGradientSignals( smaLookback, daysOfSmaGradient, GradientType.POSITIVE, MATH_CONTEXT ); //TODO Create RSI final List<IndicatorSignalGenerator> generators = new ArrayList<IndicatorSignalGenerator>(); generators.add( macd ); generators.add( sma ); final List<SignalFilter> filters = new ArrayList<SignalFilter>(); final SignalFilter filter = new RollingTimePeriodSignalFilterDecorator( new IndicatorsOnSameDaySignalFilter( IndicatorSignalType.MACD,IndicatorSignalType.SMA, IndicatorSignalType.RSI ), Period.ofDays( 5 ) ); filters.add( filter ); final ProcessLongBuySignals buyLong = new ProcessLongBuySignals( generators, filters ); final Map<Equity, List<BuySignal>> buyLongSignals = new EnumMap<Equity, List<BuySignal>>( Equity.class ); for (final Equity equity : Equity.values()) { final TradingDayPrices[] dataPoints = getDataPoints( equity, startDate, endDate ); final List<BuySignal> signals = buyLong.process( equity, dataPoints ); buyLongSignals.put( equity, signals ); } displayBuySignals( buyLongSignals ); HibernateUtil.getSessionFactory().close(); } private static void updateEquities() { final DataServiceUpdater updateService = DataServiceUpdaterImpl.getInstance(); final LocalDate endDate = LocalDate.now(); final LocalDate startDate = endDate.minus( HISTORY_REQUIRED, ChronoUnit.DAYS ); for (final Equity equity : Equity.values()) { updateService.get( equity.getSymbol(), startDate, endDate ); } } private static void displayBuySignals( final Map<Equity, List<BuySignal>> buyLongSignals ) { final DisplayBuySignals display = new DisplayBuySignals( OLDEST_SIGNAL ); for (final Equity equity : buyLongSignals.keySet()) { final String symbol = equity.getSymbol(); display.displayBuySignals( symbol, buyLongSignals.get( equity ) ); } } private static TradingDayPrices[] getDataPoints( final Equity equity, final LocalDate startDate, final LocalDate endDate ) { final DataService service = HibernateDataService.getInstance(); final String tickerSymbol = equity.getSymbol(); final TradingDayPrices[] data = service.get( tickerSymbol, startDate, endDate ); LOG.info( String.format( "%s data points returned: %s", tickerSymbol, data == null ? null : data.length ) ); return data; } }
package com.yahoo.document.restapi; import com.yahoo.document.Document; import com.yahoo.document.DocumentId; import com.yahoo.document.DocumentRemove; import com.yahoo.document.TestAndSetCondition; import com.yahoo.document.json.JsonWriter; import com.yahoo.document.DocumentPut; import com.yahoo.documentapi.DocumentAccess; import com.yahoo.documentapi.DocumentAccessException; import com.yahoo.documentapi.SyncParameters; import com.yahoo.documentapi.SyncSession; import com.yahoo.documentapi.VisitorControlHandler; import com.yahoo.documentapi.VisitorParameters; import com.yahoo.documentapi.VisitorSession; import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol; import com.yahoo.messagebus.StaticThrottlePolicy; import com.yahoo.storage.searcher.ContinuationHit; import com.yahoo.vdslib.VisitorOrdering; import com.yahoo.vespaclient.ClusterDef; import com.yahoo.vespaclient.ClusterList; import com.yahoo.vespaxmlparser.VespaXMLFeedReader; import com.yahoo.yolean.concurrent.ConcurrentResourcePool; import com.yahoo.yolean.concurrent.ResourceFactory; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; import java.util.Set; /** * Sends operations to messagebus via document api. * * @author dybis */ public class OperationHandlerImpl implements OperationHandler { public static final int VISIT_TIMEOUT_MS = 120000; private final DocumentAccess documentAccess; private static final class SyncSessionFactory extends ResourceFactory<SyncSession> { private final DocumentAccess documentAccess; SyncSessionFactory(DocumentAccess documentAccess) { this.documentAccess = documentAccess; } @Override public SyncSession create() { return documentAccess.createSyncSession(new SyncParameters()); } } private final ConcurrentResourcePool<SyncSession> syncSessions; public OperationHandlerImpl(DocumentAccess documentAccess) { this.documentAccess = documentAccess; syncSessions = new ConcurrentResourcePool<>(new SyncSessionFactory(documentAccess)); } @Override public void shutdown() { for (SyncSession session : syncSessions) { session.destroy(); } documentAccess.shutdown(); } private static final int HTTP_STATUS_BAD_REQUEST = 400; private static final int HTTP_STATUS_INSUFFICIENT_STORAGE = 507; private static int getHTTPStatusCode(Set<Integer> errorCodes) { if (errorCodes.size() == 1 && errorCodes.contains(DocumentProtocol.ERROR_NO_SPACE)) { return HTTP_STATUS_INSUFFICIENT_STORAGE; } return HTTP_STATUS_BAD_REQUEST; } private static Response createErrorResponse(DocumentAccessException documentException, RestUri restUri) { return Response.createErrorResponse(getHTTPStatusCode(documentException.getErrorCodes()), documentException.getMessage(), restUri); } @Override public VisitResult visit( RestUri restUri, String documentSelection, Optional<String> cluster, Optional<String> continuation) throws RestApiException { VisitorParameters visitorParameters = createVisitorParameters(restUri, documentSelection, cluster, continuation); VisitorControlHandler visitorControlHandler = new VisitorControlHandler(); visitorParameters.setControlHandler(visitorControlHandler); LocalDataVisitorHandler localDataVisitorHandler = new LocalDataVisitorHandler(); visitorParameters.setLocalDataHandler(localDataVisitorHandler); final VisitorSession visitorSession; try { visitorSession = documentAccess.createVisitorSession(visitorParameters); // Not sure if this line is required visitorControlHandler.setSession(visitorSession); } catch (Exception e) { throw new RestApiException(Response.createErrorResponse( 500, "Failed during parsing of arguments for visiting: " + ExceptionUtils.getStackTrace(e), restUri)); } try { return doVisit(visitorControlHandler, localDataVisitorHandler, restUri); } finally { visitorSession.destroy(); } } private VisitResult doVisit( VisitorControlHandler visitorControlHandler, LocalDataVisitorHandler localDataVisitorHandler, RestUri restUri) throws RestApiException { try { if (! visitorControlHandler.waitUntilDone(VISIT_TIMEOUT_MS)) { throw new RestApiException(Response.createErrorResponse(500, "Timed out", restUri)); } if (visitorControlHandler.getResult().code != VisitorControlHandler.CompletionCode.SUCCESS) { throw new RestApiException(Response.createErrorResponse(400, visitorControlHandler.getResult().toString())); } } catch (InterruptedException e) { throw new RestApiException(Response.createErrorResponse(500, ExceptionUtils.getStackTrace(e), restUri)); } if (localDataVisitorHandler.getErrors().isEmpty()) { final Optional<String> continuationToken; if (! visitorControlHandler.getProgress().isFinished()) { final ContinuationHit continuationHit = new ContinuationHit(visitorControlHandler.getProgress()); continuationToken = Optional.of(continuationHit.getValue()); } else { continuationToken = Optional.empty(); } return new VisitResult(continuationToken, localDataVisitorHandler.getCommaSeparatedJsonDocuments()); } throw new RestApiException(Response.createErrorResponse(500, localDataVisitorHandler.getErrors(), restUri)); } @Override public void put(RestUri restUri, VespaXMLFeedReader.Operation data) throws RestApiException { SyncSession syncSession = syncSessions.alloc(); try { DocumentPut put = new DocumentPut(data.getDocument()); put.setCondition(data.getCondition()); syncSession.put(put); } catch (DocumentAccessException documentException) { throw new RestApiException(createErrorResponse(documentException, restUri)); } catch (Exception e) { throw new RestApiException(Response.createErrorResponse(500, ExceptionUtils.getStackTrace(e), restUri)); } finally { syncSessions.free(syncSession); } } @Override public void update(RestUri restUri, VespaXMLFeedReader.Operation data) throws RestApiException { SyncSession syncSession = syncSessions.alloc(); try { syncSession.update(data.getDocumentUpdate()); } catch (DocumentAccessException documentException) { throw new RestApiException(createErrorResponse(documentException, restUri)); } catch (Exception e) { throw new RestApiException(Response.createErrorResponse(500, ExceptionUtils.getStackTrace(e), restUri)); } finally { syncSessions.free(syncSession); } } @Override public void delete(RestUri restUri, String condition) throws RestApiException { SyncSession syncSession = syncSessions.alloc(); try { DocumentId id = new DocumentId(restUri.generateFullId()); DocumentRemove documentRemove = new DocumentRemove(id); if (condition != null && ! condition.isEmpty()) { documentRemove.setCondition(new TestAndSetCondition(condition)); } syncSession.remove(documentRemove); } catch (DocumentAccessException documentException) { throw new RestApiException(Response.createErrorResponse(400, documentException.getMessage(), restUri)); } catch (Exception e) { throw new RestApiException(Response.createErrorResponse(500, ExceptionUtils.getStackTrace(e), restUri)); } finally { syncSessions.free(syncSession); } } @Override public Optional<String> get(RestUri restUri) throws RestApiException { SyncSession syncSession = syncSessions.alloc(); try { DocumentId id = new DocumentId(restUri.generateFullId()); final Document document = syncSession.get(id); if (document == null) { return Optional.empty(); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonWriter jsonWriter = new JsonWriter(outputStream); jsonWriter.write(document); return Optional.of(outputStream.toString(StandardCharsets.UTF_8.name())); } catch (Exception e) { throw new RestApiException(Response.createErrorResponse(500, ExceptionUtils.getStackTrace(e), restUri)); } finally { syncSessions.free(syncSession); } } private static String resolveClusterRoute(Optional<String> wantedCluster) throws RestApiException { List<ClusterDef> clusters = new ClusterList("client").getStorageClusters(); return resolveClusterRoute(wantedCluster, clusters); } // Based on resolveClusterRoute in VdsVisit, protected for testability protected static String resolveClusterRoute(Optional<String> wantedCluster, List<ClusterDef> clusters) throws RestApiException { if (clusters.size() == 0) { throw new IllegalArgumentException("Your Vespa cluster does not have any content clusters " + "declared. Visiting feature is not available."); } if (! wantedCluster.isPresent()) { if (clusters.size() != 1) { new RestApiException(Response.createErrorResponse(400, "Several clusters exist: " + clusterListToString(clusters) + " you must specify one.. ")); } return clusterDefToRoute(clusters.get(0)); } for (ClusterDef clusterDef : clusters) { if (clusterDef.getName().equals(wantedCluster.get())) { return clusterDefToRoute(clusterDef); } } throw new RestApiException(Response.createErrorResponse(400, "Your vespa cluster contains the content clusters " + clusterListToString(clusters) + " not " + wantedCluster.get() + ". Please select a valid vespa cluster.")); } private static String clusterDefToRoute(ClusterDef clusterDef) { return "[Storage:cluster=" + clusterDef.getName() + ";clusterconfigid=" + clusterDef.getConfigId() + "]"; } private static String clusterListToString(List<ClusterDef> clusters) { StringBuilder clusterListString = new StringBuilder(); clusters.forEach(x -> clusterListString.append(x.getName()).append(" (").append(x.getConfigId()).append("), ")); return clusterListString.toString(); } private VisitorParameters createVisitorParameters( RestUri restUri, String documentSelection, Optional<String> clusterName, Optional<String> continuation) throws RestApiException { StringBuilder selection = new StringBuilder(); if (! documentSelection.isEmpty()) { selection.append("(").append(documentSelection).append(" and "); } selection.append(restUri.getDocumentType()).append(" and (id.namespace=='").append(restUri.getNamespace()).append("')"); if (! documentSelection.isEmpty()) { selection.append(")"); } VisitorParameters params = new VisitorParameters(selection.toString()); // Only return fieldset that is part of the document. params.fieldSet(restUri.getDocumentType() + ":[document]"); params.setMaxBucketsPerVisitor(1); params.setMaxPending(32); params.setMaxFirstPassHits(1); params.setMaxTotalHits(10); params.setThrottlePolicy(new StaticThrottlePolicy().setMaxPendingCount(1)); params.setToTimestamp(0L); params.setFromTimestamp(0L); params.visitInconsistentBuckets(true); params.setVisitorOrdering(VisitorOrdering.ASCENDING); params.setRoute(resolveClusterRoute(clusterName)); params.setTraceLevel(0); params.setPriority(DocumentProtocol.Priority.NORMAL_4); params.setVisitRemoves(false); if (continuation.isPresent()) { try { params.setResumeToken(ContinuationHit.getToken(continuation.get())); } catch (Exception e) { throw new RestApiException(Response.createErrorResponse(500, ExceptionUtils.getStackTrace(e), restUri)); } } return params; } }
package teams.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import teams.api.validations.TeamValidator; import teams.domain.*; import teams.exception.ResourceNotFoundException; import teams.repository.PersonRepository; import javax.mail.MessagingException; import java.io.IOException; import java.util.List; import java.util.Map; import static java.util.stream.Collectors.toList; @RestController public class SpDashboardController extends ApiController implements TeamValidator { private final PersonRepository personRepository; private final Map<String, String> productConfig; private final String spDashboardPersonUrn; private final String spDashboardPersonEmail; private final String spDashboardPersonName; @Autowired public SpDashboardController(PersonRepository personRepository, @Qualifier("productConfig") Map<String, String> productConfig, @Value("${sp_dashboard.person-urn}") String spDashboardPersonUrn, @Value("${sp_dashboard.email}") String spDashboardPersonEmail, @Value("${sp_dashboard.name}") String spDashboardPersonName) { this.personRepository = personRepository; this.productConfig = productConfig; this.spDashboardPersonUrn = spDashboardPersonUrn; this.spDashboardPersonEmail = spDashboardPersonEmail; this.spDashboardPersonName = spDashboardPersonName; } @GetMapping("api/spdashboard/teams/{urn:.+}") public Team teamByUrn(@PathVariable("urn") String urn) { Team team = teamRepository.findByUrn(urn).orElseThrow(() -> new ResourceNotFoundException(String.format("Team with urn %s does not exists", urn))); team.setUrn(urn); team.getInvitations() //lazy load messages .forEach(invitation -> invitation.getInvitationMessages().forEach(InvitationMessage::getMessage)); team.getMemberships().forEach(membership -> membership.getPerson().isValid()); return team; } @PostMapping("api/spdashboard/teams") public Team createTeam(@Validated @RequestBody NewTeamProperties teamProperties) throws IOException, MessagingException { return doCreateTeam(teamProperties, this.federatedUser()); } @PutMapping("api/spdashboard/memberships") public ResponseEntity changeMembership(@Validated @RequestBody MembershipProperties membershipProperties) { Membership membership = membershipRepository.findOne(membershipProperties.getId()); Role futureRole = membershipProperties.getRole(); log.info("Changing current {} membership of {} in team {} to {} by {}", membership.getRole(), membership.getPerson().getUrn(), membership.getTeam().getUrn(), futureRole, "SP Dashboard"); membership.setRole(futureRole); membershipRepository.save(membership); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PostMapping("api/spdashboard/invites") public ResponseEntity invites(@Validated @RequestBody ClientInvitation clientInvitation) { Person person = this.federatedUser().getPerson(); Team team = teamById(clientInvitation.getTeamId(), false); List<String> emails = clientInvitation.getEmails(); List<Invitation> invitations = emails.stream().map(email -> new Invitation( team, email, clientInvitation.getIntendedRole(), clientInvitation.getLanguage(), clientInvitation.getExpiryDate()).addInvitationMessage(person, clientInvitation.getMessage())) .collect(toList()); log.info("Saving {} invitations for emails: {}", invitations.size(), String.join(",", emails)); saveAndSendInvitation(invitations, team, person, this.federatedUser()); return ResponseEntity.status(HttpStatus.CREATED).build(); } @PutMapping("api/spdashboard/invites") public ResponseEntity resend(@Validated @RequestBody ClientResendInvitation resendInvitation) throws IOException, MessagingException { Long invitationId = resendInvitation.getId(); Invitation invitation = invitationRepository.findOne(invitationId); invitation.addInvitationMessage(this.federatedUser().getPerson(), resendInvitation.getMessage()); log.info("Resending mail to {}", invitation.getEmail()); invitationRepository.save(invitation); mailBox.sendInviteMail(invitation, this.federatedUser()); return ResponseEntity.status(HttpStatus.CREATED).build(); } private FederatedUser federatedUser() { Person person = personRepository.findByUrnIgnoreCase(spDashboardPersonUrn).orElseGet(() -> personRepository.save(new Person(spDashboardPersonUrn, spDashboardPersonName, spDashboardPersonEmail, false, false))); return new FederatedUser(person, productConfig.get("productName"), productConfig); } @DeleteMapping("api/spdashboard/teams/{id}") public ResponseEntity deleteTeam(@PathVariable("id") Long id) { Team team = teamRepository.findOne(id); log.info("Deleting team {}", team.getName()); teamRepository.delete(team); return ResponseEntity.status(HttpStatus.CREATED).build(); } @DeleteMapping("api/spdashboard/memberships/{membershipId}") public ResponseEntity deleteMembership(@PathVariable("membershipId") Long membershipId) { Membership membership = membershipRepository.findOne(membershipId); log.info("Deleting membership {} from team {}", membership.getPerson().getUrn(), membership.getTeam().getUrn()); membershipRepository.delete(membership); return ResponseEntity.status(HttpStatus.CREATED).build(); } }
package org.cytoscape.view.vizmap.gui.internal.view; import static javax.swing.GroupLayout.DEFAULT_SIZE; import static javax.swing.GroupLayout.PREFERRED_SIZE; import static org.cytoscape.util.swing.LookAndFeelUtil.createTitledBorder; import static org.cytoscape.util.swing.LookAndFeelUtil.equalizeSize; import static org.cytoscape.util.swing.LookAndFeelUtil.isAquaLAF; import java.awt.Component; import java.awt.Dimension; import java.util.Collection; import java.util.Collections; import javax.swing.DefaultListCellRenderer; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import org.cytoscape.application.swing.CyColumnComboBox; import org.cytoscape.application.swing.CyColumnPresentationManager; import org.cytoscape.model.CyColumn; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNetworkTableManager; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyTable; import org.cytoscape.util.swing.IconManager; import org.cytoscape.util.swing.TextIcon; import org.cytoscape.view.vizmap.gui.internal.util.ServicesUtil; import org.cytoscape.view.vizmap.gui.internal.view.util.IconUtil; @SuppressWarnings("serial") public class ColumnStylePanel { private final ServicesUtil servicesUtil; private OptionsButton optionsBtn; private JComboBox<CyTable> tableCombo; private CyColumnComboBox columnCombo; private JPanel columnPanel; public ColumnStylePanel(ServicesUtil servicesUtil) { this.servicesUtil = servicesUtil; } public JComponent getComponent() { return getColumnPanel(); } public JPanel getColumnPanel() { if (columnPanel == null) { columnPanel = new JPanel(); columnPanel.setOpaque(!isAquaLAF()); columnPanel.setBorder(createTitledBorder("Apply Style To:")); // TODO: For some reason, the Styles button is naturally taller than the Options one on Nimbus and Windows. // Let's force it to have the same height. getColumnComboBox().setPreferredSize( new Dimension(getColumnComboBox().getPreferredSize().width, getOptionsBtn().getOptionsBtn().getPreferredSize().height)); var layout = new GroupLayout(columnPanel); columnPanel.setLayout(layout); layout.setAutoCreateContainerGaps(true); layout.setAutoCreateGaps(!isAquaLAF()); var tableLbl = new JLabel("Table:"); var columnLbl = new JLabel("Column:"); layout.setHorizontalGroup( layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addComponent(tableLbl, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) .addComponent(getTableComboBox(), DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE) ) .addGroup(layout.createSequentialGroup() .addComponent(columnLbl, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) .addComponent(getColumnComboBox(), DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(getOptionsBtn().getOptionsBtn(), PREFERRED_SIZE, 64, PREFERRED_SIZE) ) ); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.CENTER, false) .addComponent(tableLbl, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) .addComponent(getTableComboBox(), PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) ) .addGroup(layout.createParallelGroup(Alignment.CENTER, false) .addComponent(columnLbl, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) .addComponent(getColumnComboBox(), PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) .addComponent(getOptionsBtn().getOptionsBtn(), PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE) ) ); equalizeSize(tableLbl, columnLbl); } return columnPanel; } JComboBox<CyTable> getTableComboBox() { if (tableCombo == null) { tableCombo = new JComboBox<>(); var netTableManager = servicesUtil.get(CyNetworkTableManager.class); var iconManager = servicesUtil.get(IconManager.class); var globalTableIcon = new TextIcon(IconManager.ICON_TABLE, iconManager.getIconFont(14.0f), 16, 16); var iconFont = iconManager.getIconFont(IconUtil.CY_FONT_NAME, 14.0f); var nodeTableIcon = new TextIcon(IconUtil.NODE_TABLE, iconFont, 16, 16); var edgeTableIcon = new TextIcon(IconUtil.EDGE_TABLE, iconFont, 16, 16); var netTableIcon = new TextIcon(IconUtil.NETWORK_TABLE, iconFont, 16, 16); tableCombo.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { var comp = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value == null) { setText("-- None --"); setIcon(null); } else { var table = (CyTable) value; var text = table.getTitle(); var icon = globalTableIcon; var namespace = netTableManager.getTableNamespace(table); var type = netTableManager.getTableType(table); if (type != null && CyNetwork.DEFAULT_ATTRS.equals(namespace)) text = "Default " + type.getSimpleName().replace("Cy", ""); if (type == CyNode.class) icon = nodeTableIcon; else if (type == CyEdge.class) icon = edgeTableIcon; else if (type == CyNetwork.class) icon = netTableIcon; comp.setText(text); comp.setIcon(icon); } return comp; } }); } return tableCombo; } CyColumnComboBox getColumnComboBox() { if (columnCombo == null) { var columnPresentationManager = servicesUtil.get(CyColumnPresentationManager.class); columnCombo = new CyColumnComboBox(columnPresentationManager, Collections.emptyList()); } return columnCombo; } OptionsButton getOptionsBtn() { if (optionsBtn == null) { optionsBtn = new OptionsButton(servicesUtil); } return optionsBtn; } public void updateColumns(Collection<CyTable> tables, CyTable selTable, Collection<CyColumn> columns, CyColumn selColumn) { var tableComboBox = getTableComboBox(); tableComboBox.removeAllItems(); if (tables != null) tables.forEach(tableComboBox::addItem); if (selTable != null) tableComboBox.setSelectedItem(selTable); var columnComboBox = getColumnComboBox(); columnComboBox.removeAllItems(); if (columns != null) columns.forEach(columnComboBox::addItem); if (selColumn != null) columnComboBox.setSelectedItem(selColumn); update(); } private void update() { getTableComboBox().setEnabled(getTableComboBox().getItemCount() > 0); getColumnComboBox().setEnabled(getColumnComboBox().getItemCount() > 0); getOptionsBtn().getOptionsBtn().setEnabled(getColumnComboBox().getItemCount() > 0); } }
package org.weasis.dicom.explorer.wado; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.JProgressBar; import javax.swing.SwingWorker; import org.dcm4che2.data.DicomObject; import org.dcm4che2.data.VRMap; import org.dcm4che2.io.DicomInputStream; import org.dcm4che2.io.DicomOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.weasis.core.api.explorer.ObservableEvent; import org.weasis.core.api.gui.task.CircularProgressBar; import org.weasis.core.api.gui.task.SeriesProgressMonitor; import org.weasis.core.api.gui.util.AbstractProperties; import org.weasis.core.api.gui.util.GuiExecutor; import org.weasis.core.api.media.data.MediaElement; import org.weasis.core.api.media.data.MediaSeries; import org.weasis.core.api.media.data.MediaSeriesGroup; import org.weasis.core.api.media.data.Series; import org.weasis.core.api.media.data.SeriesImporter; import org.weasis.core.api.media.data.TagW; import org.weasis.core.api.media.data.TagW.TagType; import org.weasis.core.api.media.data.Thumbnail; import org.weasis.core.api.service.BundleTools; import org.weasis.core.api.util.FileUtil; import org.weasis.core.ui.docking.UIManager; import org.weasis.core.ui.editor.SeriesViewerFactory; import org.weasis.core.ui.editor.ViewerPluginBuilder; import org.weasis.core.ui.editor.image.ViewerPlugin; import org.weasis.dicom.codec.DicomInstance; import org.weasis.dicom.codec.DicomMediaIO; import org.weasis.dicom.codec.TransferSyntax; import org.weasis.dicom.codec.wado.WadoParameters; import org.weasis.dicom.codec.wado.WadoParameters.HttpTag; import org.weasis.dicom.explorer.DicomExplorer; import org.weasis.dicom.explorer.DicomModel; import org.weasis.dicom.explorer.MimeSystemAppFactory; public class LoadSeries extends SwingWorker<Boolean, Void> implements SeriesImporter { private static final Logger log = LoggerFactory.getLogger(LoadSeries.class); public static final String CODOWNLOAD_IMAGES_NB = "wado.codownload.images.nb"; //$NON-NLS-1$ public static final int CODOWNLOAD_NUMBER = BundleTools.SYSTEM_PREFERENCES.getIntProperty(CODOWNLOAD_IMAGES_NB, 4); public static final File DICOM_EXPORT_DIR = new File(AbstractProperties.APP_TEMP_DIR, "dicom"); //$NON-NLS-1$ public static final File DICOM_TMP_DIR = new File(AbstractProperties.APP_TEMP_DIR, "tmp"); //$NON-NLS-1$ static { try { DICOM_TMP_DIR.mkdirs(); DICOM_EXPORT_DIR.mkdir(); } catch (Exception e) { e.printStackTrace(); } } private static final ExecutorService executor = Executors.newFixedThreadPool(3); public enum Status { Downloading, Paused, Complete, Cancelled, Error }; private final DicomModel dicomModel; private final Series dicomSeries; private final JProgressBar progressBar; private DownloadPriority priority = null; public LoadSeries(Series dicomSeries, DicomModel dicomModel) { if (dicomModel == null || dicomSeries == null) { throw new IllegalArgumentException("null parameters"); //$NON-NLS-1$ } this.dicomModel = dicomModel; this.dicomSeries = dicomSeries; final List<DicomInstance> sopList = (List<DicomInstance>) dicomSeries.getTagValue(TagW.WadoInstanceReferenceList); // Trick to keep progressBar with a final modifier. The progressBar must be instantiated in EDT (required by // substance) final CircularProgressBar[] bar = new CircularProgressBar[1]; GuiExecutor.instance().invokeAndWait(new Runnable() { @Override public void run() { bar[0] = new CircularProgressBar(0, sopList.size()); } }); this.progressBar = bar[0]; this.dicomSeries.setSeriesLoader(this); } public LoadSeries(Series dicomSeries, DicomModel dicomModel, JProgressBar progressBar) { if (dicomModel == null || dicomSeries == null || progressBar == null) { throw new IllegalArgumentException("null parameters"); //$NON-NLS-1$ } this.dicomModel = dicomModel; this.dicomSeries = dicomSeries; this.progressBar = progressBar; this.dicomSeries.setSeriesLoader(this); } @Override protected Boolean doInBackground() { return startDownload(); } @Override public JProgressBar getProgressBar() { return progressBar; } @Override public boolean isStopped() { return isCancelled(); } @Override public boolean stop() { if (!isDone()) { boolean val = cancel(true); dicomSeries.setSeriesLoader(this); return val; } return true; } @Override public void resume() { if (isStopped()) { LoadSeries taskResume = new LoadSeries(dicomSeries, dicomModel, progressBar); DownloadPriority p = this.getPriority(); p.setPriority(DownloadPriority.COUNTER.getAndDecrement()); taskResume.setPriority(p); Thumbnail thumbnail = (Thumbnail) this.getDicomSeries().getTagValue(TagW.Thumbnail); if (thumbnail != null) { LoadSeries.removeAnonymousMouseAndKeyListener(thumbnail); thumbnail.addMouseListener(DicomExplorer.createThumbnailMouseAdapter(taskResume.getDicomSeries(), dicomModel, taskResume)); thumbnail.addKeyListener(DicomExplorer.createThumbnailKeyListener(taskResume.getDicomSeries(), dicomModel)); } LoadRemoteDicomManifest.loadingQueue.offer(taskResume); LoadRemoteDicomManifest.addLoadSeries(taskResume, dicomModel); LoadRemoteDicomManifest.removeLoadSeries(this, dicomModel); } } @Override protected void done() { if (!isStopped()) { LoadRemoteDicomManifest.removeLoadSeries(this, dicomModel); Thumbnail thumbnail = (Thumbnail) dicomSeries.getTagValue(TagW.Thumbnail); if (thumbnail != null) { thumbnail.setProgressBar(null); thumbnail.repaint(); } Integer splitNb = (Integer) dicomSeries.getTagValue(TagW.SplitSeriesNumber); Object dicomObject = dicomSeries.getTagValue(TagW.DicomSpecialElement); if (splitNb != null || dicomObject != null) { dicomModel.firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Update, dicomModel, null, dicomSeries)); } else if (dicomSeries.size() == 0) { // Remove in case of split Series and all the SopInstanceUIDs already exist dicomModel.firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Remove, dicomModel, null, dicomSeries)); } this.dicomSeries.setSeriesLoader(null); } } private boolean isSOPInstanceUIDExist(MediaSeriesGroup study, Series dicomSeries, String sopUID) { if (dicomSeries.hasMediaContains(TagW.SOPInstanceUID, sopUID)) { return true; } // Search in split Series, cannot use "has this series a SplitNumber" because splitting can be executed later // for Dicom Video and other special Dicom String uid = (String) dicomSeries.getTagValue(TagW.SeriesInstanceUID); if (study != null && uid != null) { Collection<MediaSeriesGroup> seriesList = dicomModel.getChildren(study); for (Iterator<MediaSeriesGroup> it = seriesList.iterator(); it.hasNext();) { MediaSeriesGroup group = it.next(); if (dicomSeries != group && group instanceof Series) { Series s = (Series) group; if (uid.equals(s.getTagValue(TagW.SeriesInstanceUID))) { if (s.hasMediaContains(TagW.SOPInstanceUID, sopUID)) { return true; } } } } } return false; } private void incrementProgressBarValue() { GuiExecutor.instance().execute(new Runnable() { @Override public void run() { progressBar.setValue(progressBar.getValue() + 1); } }); } private Boolean startDownload() { MediaSeriesGroup patient = dicomModel.getParent(dicomSeries, DicomModel.patient); MediaSeriesGroup study = dicomModel.getParent(dicomSeries, DicomModel.study); log.info("Downloading series of {} [{}]", patient, dicomSeries); //$NON-NLS-1$ final List<DicomInstance> sopList = (List<DicomInstance>) dicomSeries.getTagValue(TagW.WadoInstanceReferenceList); final WadoParameters wado = (WadoParameters) dicomSeries.getTagValue(TagW.WadoParameters); if (wado == null) { return false; } ExecutorService imageDownloader = Executors.newFixedThreadPool(CODOWNLOAD_NUMBER); ArrayList<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(sopList.size()); int[] dindex = generateDownladOrder(sopList.size()); GuiExecutor.instance().execute(new Runnable() { @Override public void run() { progressBar.setValue(0); } }); for (int k = 0; k < sopList.size(); k++) { DicomInstance instance = sopList.get(dindex[k]); if (isCancelled()) { return true; } // Test if SOPInstanceUID already exists if (isSOPInstanceUIDExist(study, dicomSeries, instance.getSopInstanceUID())) { incrementProgressBarValue(); log.debug("DICOM instance {} already exists, skip.", instance.getSopInstanceUID()); //$NON-NLS-1$ continue; } URL url = null; try { String studyUID = ""; //$NON-NLS-1$ String seriesUID = ""; //$NON-NLS-1$ if (!wado.isRequireOnlySOPInstanceUID()) { studyUID = (String) study.getTagValue(TagW.StudyInstanceUID); seriesUID = (String) dicomSeries.getTagValue(TagW.SeriesInstanceUID); } StringBuffer request = new StringBuffer(wado.getWadoURL()); if (instance.getDirectDownloadFile() == null) { request.append("?requestType=WADO&studyUID="); //$NON-NLS-1$ request.append(studyUID); request.append("&seriesUID="); //$NON-NLS-1$ request.append(seriesUID); request.append("&objectUID="); //$NON-NLS-1$ request.append(instance.getSopInstanceUID()); request.append("&contentType=application%2Fdicom"); //$NON-NLS-1$ TransferSyntax transcoding = DicomManager.getInstance().getWadoTSUID(); if (transcoding.getTransferSyntaxUID() != null) { dicomSeries.setTag(TagW.WadoTransferSyntaxUID, transcoding.getTransferSyntaxUID()); } // for dcm4chee: it gets original DICOM files when no TransferSyntax is specified String wado_tsuid = (String) dicomSeries.getTagValue(TagW.WadoTransferSyntaxUID); if (wado_tsuid != null && !wado_tsuid.equals("")) { //$NON-NLS-1$ // On Mac and Win 64 some decoders (J2KImageReaderCodecLib) are missing, ask for uncompressed // syntax for TSUID: 1.2.840.10008.1.2.4.50, 1.2.840.10008.1.2.4.51, 1.2.840.10008.1.2.4.57 // 1.2.840.10008.1.2.4.70 1.2.840.10008.1.2.4.80, 1.2.840.10008.1.2.4.81 // Solaris has all the decoders, but no bundle has been built for Weasis String osName = AbstractProperties.OPERATING_SYSTEM; if (!(osName.startsWith("win") && "x86".equals(System.getProperty("os.arch"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ && !osName.startsWith("linux")) { //$NON-NLS-1$ if (wado_tsuid.startsWith("1.2.840.10008.1.2.4.5") //$NON-NLS-1$ || wado_tsuid.startsWith("1.2.840.10008.1.2.4.7") //$NON-NLS-1$ || wado_tsuid.startsWith("1.2.840.10008.1.2.4.8")) { //$NON-NLS-1$ wado_tsuid = TransferSyntax.EXPLICIT_VR_LE.getTransferSyntaxUID(); } } request.append("&transferSyntax="); //$NON-NLS-1$ request.append(wado_tsuid); if (transcoding.getTransferSyntaxUID() != null) { dicomSeries.setTag(TagW.WadoCompressionRate, transcoding.getCompression()); } Integer rate = (Integer) dicomSeries.getTagValue(TagW.WadoCompressionRate); if (rate != null && rate > 0) { request.append("&imageQuality="); //$NON-NLS-1$ request.append(rate); } } } else { request.append(instance.getDirectDownloadFile()); } request.append(wado.getAdditionnalParameters()); url = new URL(request.toString()); } catch (MalformedURLException e1) { log.error(e1.getMessage(), e1.getCause()); continue; } log.debug("Download DICOM instance {} index {}.", url, k); //$NON-NLS-1$ Download ref = new Download(url, wado); tasks.add(ref); // Future future = imageDownloader.submit(ref); // try { // Object series = future.get(); // catch (InterruptedException e) { // // Re-assert the thread's interrupted status // Thread.currentThread().interrupt(); // // We don't need the result, so cancel the task too // future.cancel(true); // catch (ExecutionException e) { } try { imageDownloader.invokeAll(tasks); } catch (InterruptedException e) { } imageDownloader.shutdown(); return true; } public void startDownloadImageReference(final WadoParameters wadoParameters) { final List<DicomInstance> sopList = (List<DicomInstance>) dicomSeries.getTagValue(TagW.WadoInstanceReferenceList); if (sopList.size() > 0) { // Sort the UIDs for building the thumbnail that is in the middle of // the Series Collections.sort(sopList, new Comparator<DicomInstance>() { @Override public int compare(DicomInstance dcm1, DicomInstance dcm2) { int nubmer1 = dcm1.getInstanceNumber(); int nubmer2 = dcm2.getInstanceNumber(); if (nubmer1 == -1 && nubmer2 == -1) { String str1 = dcm1.getSopInstanceUID(); String str2 = dcm2.getSopInstanceUID(); int length1 = str1.length(); int length2 = str2.length(); if (length1 < length2) { char[] c = new char[length2 - length1]; for (int i = 0; i < c.length; i++) { c[i] = '0'; } int index = str1.lastIndexOf(".") + 1; //$NON-NLS-1$ str1 = str1.substring(0, index) + new String(c) + str1.substring(index); } else if (length1 > length2) { char[] c = new char[length1 - length2]; for (int i = 0; i < c.length; i++) { c[i] = '0'; } int index = str2.lastIndexOf(".") + 1; //$NON-NLS-1$ str2 = str2.substring(0, index) + new String(c) + str2.substring(index); } return str1.compareTo(str2); } else { return (nubmer1 < nubmer2 ? -1 : (nubmer1 == nubmer2 ? 0 : 1)); } } }); final DicomInstance instance = sopList.get(sopList.size() / 2); GuiExecutor.instance().execute(new Runnable() { @Override public void run() { Thumbnail thumbnail = (Thumbnail) dicomSeries.getTagValue(TagW.Thumbnail); if (thumbnail == null) { thumbnail = new Thumbnail(dicomSeries, null, Thumbnail.DEFAULT_SIZE); } // In case series is downloaded or canceled if (LoadSeries.this.isDone()) { thumbnail.setProgressBar(null); thumbnail.repaint(); } else { thumbnail.setProgressBar(progressBar); } addListenerToThumbnail(thumbnail, LoadSeries.this, dicomModel); thumbnail.registerListeners(); dicomSeries.setTag(TagW.Thumbnail, thumbnail); dicomModel.firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Add, dicomModel, null, dicomSeries)); } }); Runnable thumbnailLoader = new Runnable() { @Override public void run() { String studyUID = ""; //$NON-NLS-1$ String seriesUID = ""; //$NON-NLS-1$ if (!wadoParameters.isRequireOnlySOPInstanceUID()) { MediaSeriesGroup study = dicomModel.getParent(dicomSeries, DicomModel.study); studyUID = (String) study.getTagValue(TagW.StudyInstanceUID); seriesUID = (String) dicomSeries.getTagValue(TagW.SeriesInstanceUID); } File file = null; if (instance.getDirectDownloadFile() == null) { try { file = getJPEGThumnails(wadoParameters, studyUID, seriesUID, instance.getSopInstanceUID()); } catch (Exception e) { e.printStackTrace(); } } else { String thumURL = (String) dicomSeries.getTagValue(TagW.DirectDownloadThumbnail); if (thumURL != null) { try { File outFile = File.createTempFile("tumb_", FileUtil.getExtension(thumURL), //$NON-NLS-1$ AbstractProperties.APP_TEMP_DIR); int resp = FileUtil.writeFile(new URL(wadoParameters.getWadoURL() + thumURL), outFile); if (resp == -1) { file = outFile; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } if (file != null) { final File finalfile = file; GuiExecutor.instance().execute(new Runnable() { @Override public void run() { Thumbnail thumbnail = (Thumbnail) dicomSeries.getTagValue(TagW.Thumbnail); if (thumbnail != null) { thumbnail.reBuildThumbnail(finalfile, MediaSeries.MEDIA_POSITION.MIDDLE); } } }); } } }; executor.submit(thumbnailLoader); } } public static void removeAnonymousMouseAndKeyListener(Thumbnail tumbnail) { MouseListener[] listener = tumbnail.getMouseListeners(); MouseMotionListener[] motionListeners = tumbnail.getMouseMotionListeners(); KeyListener[] keyListeners = tumbnail.getKeyListeners(); MouseWheelListener[] wheelListeners = tumbnail.getMouseWheelListeners(); for (int i = 0; i < listener.length; i++) { if (listener[i].getClass().isAnonymousClass()) { tumbnail.removeMouseListener(listener[i]); } } for (int i = 0; i < motionListeners.length; i++) { if (motionListeners[i].getClass().isAnonymousClass()) { tumbnail.removeMouseMotionListener(motionListeners[i]); } } for (int i = 0; i < wheelListeners.length; i++) { if (wheelListeners[i].getClass().isAnonymousClass()) { tumbnail.removeMouseWheelListener(wheelListeners[i]); } } for (int i = 0; i < keyListeners.length; i++) { if (keyListeners[i].getClass().isAnonymousClass()) { tumbnail.removeKeyListener(keyListeners[i]); } } } private static void addListenerToThumbnail(final Thumbnail thumbnail, final LoadSeries loadSeries, final DicomModel dicomModel) { final Series series = loadSeries.getDicomSeries(); thumbnail.addMouseListener(DicomExplorer.createThumbnailMouseAdapter(series, dicomModel, loadSeries)); thumbnail.addKeyListener(DicomExplorer.createThumbnailKeyListener(series, dicomModel)); } public static void openSequenceInPlugin(SeriesViewerFactory factory, List<MediaSeries> series, DicomModel dicomModel, boolean removeOldSeries) { if (factory == null) { return; } dicomModel.firePropertyChange(new ObservableEvent(ObservableEvent.BasicAction.Register, dicomModel, null, new ViewerPluginBuilder(factory, series, dicomModel, true, removeOldSeries))); } public static void openSequenceInDefaultPlugin(List<MediaSeries> series, DicomModel dicomModel) { ArrayList<String> mimes = new ArrayList<String>(); for (MediaSeries s : series) { String mime = s.getMimeType(); if (mime != null && !mimes.contains(mime)) { mimes.add(mime); } } for (String mime : mimes) { SeriesViewerFactory plugin = UIManager.getViewerFactory(mime); if (plugin != null) { ArrayList<MediaSeries> seriesList = new ArrayList<MediaSeries>(); for (MediaSeries s : series) { if (mime.equals(s.getMimeType())) { seriesList.add(s); } } openSequenceInPlugin(plugin, seriesList, dicomModel, true); } } } public Series getDicomSeries() { return dicomSeries; } // public File getDICOMFile(String StudyUID, String SeriesUID, String // SOPInstanceUID) throws Exception { // URL url = new URL(dicomSeries.getWadoParameters().getWadoURL() + // "?requestType=WADO&studyUID=" + StudyUID // + "&seriesUID=" + SeriesUID + "&objectUID=" + SOPInstanceUID + // "&contentType=application%2Fdicom"); // HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); // // HttpURLConnection httpCon = (HttpURLConnection) // // url.openConnection(DownloadManager.PROXY); // // httpCon.setDoOutput(true); // // httpCon.setDoInput(true); // // httpCon.setRequestMethod("GET"); // // JProgressBar statusBar = new JProgressBar(); // // statusBar.setMinimum(0); // // statusBar.setMaximum(httpCon.getContentLength()); // // statusBar.setValue(0); // // statusBar.setStringPainted(true); // OutputStream tempFileStream = null; // InputStream httpStream = null; // // File outFile = new File(TEMP_DIR + SOPInstanceUID); // File tempFile = File.createTempFile("image_", ".dcm", // AbstractProperties.APP_TEMP_DIR); // tempFile.deleteOnExit(); // try { // tempFileStream = new BufferedOutputStream(new // FileOutputStream(tempFile)); // httpStream = httpCon.getInputStream(); // byte[] buffer = new byte[4096]; // int numRead; // long numWritten = 0; // while ((numRead = httpStream.read(buffer)) != -1) { // tempFileStream.write(buffer, 0, numRead); // numWritten += numRead; // // statusBar.setValue((int) numWritten); // catch (Exception e) { // e.printStackTrace(); // finally { // FileUtil.safeClose(tempFileStream); // FileUtil.safeClose(httpStream); // return tempFile; public File getJPEGThumnails(WadoParameters wadoParameters, String StudyUID, String SeriesUID, String SOPInstanceUID) throws Exception { // TODO set quality as a preference URL url = new URL(wadoParameters.getWadoURL() + "?requestType=WADO&studyUID=" + StudyUID + "&seriesUID=" + SeriesUID //$NON-NLS-1$ //$NON-NLS-2$ + "&objectUID=" + SOPInstanceUID + "&contentType=image/jpeg&imageQuality=70" + "&rows=" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + Thumbnail.MAX_SIZE + "&columns=" + Thumbnail.MAX_SIZE + wadoParameters.getAdditionnalParameters()); //$NON-NLS-1$ HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoInput(true); httpCon.setRequestMethod("GET"); //$NON-NLS-1$ // Set http login (no protection, only convert in base64) if (wadoParameters.getWebLogin() != null) { httpCon.setRequestProperty("Authorization", "Basic " + wadoParameters.getWebLogin()); //$NON-NLS-1$ //$NON-NLS-2$ } if (wadoParameters.getHttpTaglist().size() > 0) { for (HttpTag tag : wadoParameters.getHttpTaglist()) { httpCon.setRequestProperty(tag.getKey(), tag.getValue()); } } // Connect to server. httpCon.connect(); // Make sure response code is in the 200 range. if (httpCon.getResponseCode() / 100 != 2) { return null; } OutputStream out = null; InputStream in = null; File outFile = File.createTempFile("tumb_", ".jpg", AbstractProperties.APP_TEMP_DIR); //$NON-NLS-1$ //$NON-NLS-2$ try { out = new BufferedOutputStream(new FileOutputStream(outFile)); in = httpCon.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception e) { e.printStackTrace(); } finally { FileUtil.safeClose(in); FileUtil.safeClose(out); } return outFile; } // public void interruptionRequested() { // if (isCancelled()) { // return; // int response = JOptionPane.showConfirmDialog(WeasisWin.getInstance(), // "Do you really want to stop this process?", // "Stopping Process", 0); // if (response == 0) { // cancel(true); private int[] generateDownladOrder(final int size) { int[] dindex = new int[size]; if (size < 4) { for (int i = 0; i < dindex.length; i++) { dindex[i] = i; } return dindex; } boolean[] map = new boolean[size]; int pos = 0; dindex[pos++] = 0; map[0] = true; dindex[pos++] = size - 1; map[size - 1] = true; int k = (size - 1) / 2; dindex[pos++] = k; map[k] = true; while (k > 0) { int i = 1; int start = 0; while (i < map.length) { if (map[i]) { if (!map[i - 1]) { int mid = start + (i - start) / 2; map[mid] = true; dindex[pos++] = mid; } start = i; } i++; } k /= 2; } return dindex; } class Download implements Callable<Boolean> { private final URL url; // download URL private int size; // size of download in bytes private final int downloaded; // number of bytes downloaded private Status status; // current status of download private File tempFile; private final WadoParameters wadoParameters; // private Thread thread; public Download(URL url, final WadoParameters wadoParameters) { this.url = url; this.wadoParameters = wadoParameters; size = -1; downloaded = 0; status = Status.Downloading; } public File getTempFile() { return tempFile; } public String getUrl() { return url.toString(); } // Get this download's size. public int getSize() { return size; } // Get this download's progress. public float getProgress() { return ((float) downloaded / size) * 100; } public Status getStatus() { return status; } public void pause() { status = Status.Paused; } public void resume() { status = Status.Downloading; } public void cancel() { status = Status.Cancelled; } private void error() { status = Status.Error; } // Download file. @Override public Boolean call() throws Exception { InputStream stream = null; URLConnection httpCon = null; try { // If there is a proxy, it should be already configured httpCon = url.openConnection(); // Set http login (no protection, only convert in base64) if (wadoParameters.getWebLogin() != null) { httpCon.setRequestProperty("Authorization", "Basic " + wadoParameters.getWebLogin()); //$NON-NLS-1$ //$NON-NLS-2$ } if (wadoParameters.getHttpTaglist().size() > 0) { for (HttpTag tag : wadoParameters.getHttpTaglist()) { httpCon.setRequestProperty(tag.getKey(), tag.getValue()); } } // Specify what portion of file to download. httpCon.setRequestProperty("Range", "bytes=" + downloaded + "-"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Connect to server. httpCon.connect(); } catch (IOException e) { error(); log.error("IOException for {}: {} ", url, e.getMessage()); //$NON-NLS-1$ return false; } if (httpCon instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection) httpCon).getResponseCode(); // Make sure response code is in the 200 range. if (responseCode / 100 != 2) { error(); log.error("Http Response error {} for {}", responseCode, url); //$NON-NLS-1$ return false; } } if (tempFile == null) { tempFile = File.createTempFile("image_", ".dcm", DICOM_TMP_DIR); //$NON-NLS-1$ //$NON-NLS-2$ } stream = httpCon.getInputStream(); int contentLength = httpCon.getContentLength(); contentLength = -1; if (contentLength == -1) { progressBar.setIndeterminate(progressBar.getMaximum() < 3); } else { // TODO add external circle progression } // Set the size for this download if it hasn't been already set. if (size == -1) { size = contentLength; // stateChanged(); } DicomMediaIO dicomReader = null; log.debug("Download DICOM instance {} to {}.", url, tempFile.getName()); //$NON-NLS-1$ if (dicomSeries != null) { final WadoParameters wado = (WadoParameters) dicomSeries.getTagValue(TagW.WadoParameters); int[] overrideList = wado.getOverrideDicomTagIDList(); int bytesTransferred = 0; if (overrideList == null && wado != null) { bytesTransferred = FileUtil.writeFile(new SeriesProgressMonitor(dicomSeries, stream), new FileOutputStream( tempFile)); } else if (wado != null) { bytesTransferred = writFile(new SeriesProgressMonitor(dicomSeries, stream), new FileOutputStream(tempFile), overrideList); } if (bytesTransferred >= 0) { log.warn("Download interruption {} ", url); //$NON-NLS-1$ try { tempFile.delete(); } catch (Exception e) { e.printStackTrace(); } return false; } // TODO handle file interruption // else if (bytesTransferred > 0) { // downloaded = bytesTransferred; File renameFile = new File(DICOM_EXPORT_DIR, tempFile.getName()); if (tempFile.renameTo(renameFile)) { tempFile = renameFile; } dicomReader = new DicomMediaIO(tempFile); if (dicomReader.readMediaTags()) { if (dicomSeries.size() == 0) { // Override the group (patient, study and series) by the dicom fields except the UID of // the group MediaSeriesGroup patient = dicomModel.getParent(dicomSeries, DicomModel.patient); dicomReader.writeMetaData(patient); MediaSeriesGroup study = dicomModel.getParent(dicomSeries, DicomModel.study); dicomReader.writeMetaData(study); dicomReader.writeMetaData(dicomSeries); GuiExecutor.instance().invokeAndWait(new Runnable() { @Override public void run() { Thumbnail thumb = (Thumbnail) dicomSeries.getTagValue(TagW.Thumbnail); if (thumb != null) { thumb.repaint(); } dicomModel.firePropertyChange(new ObservableEvent( ObservableEvent.BasicAction.UpdateParent, dicomModel, null, dicomSeries)); } }); } } } // Change status to complete if this point was reached because // downloading has finished. if (status == Status.Downloading) { status = Status.Complete; if (tempFile != null) { if (dicomSeries != null && dicomReader.readMediaTags()) { final DicomMediaIO reader = dicomReader; // Necessary to wait the runnable because the dicomSeries must be added to the dicomModel // before reaching done() of SwingWorker GuiExecutor.instance().invokeAndWait(new Runnable() { @Override public void run() { boolean firstImageToDisplay = false; MediaElement[] medias = reader.getMediaElement(); if (medias != null) { firstImageToDisplay = dicomSeries.size() == 0; for (MediaElement media : medias) { dicomModel.applySplittingRules(dicomSeries, media); } if (firstImageToDisplay && dicomSeries.size() == 0) { firstImageToDisplay = false; } } reader.reset(); Thumbnail thumb = (Thumbnail) dicomSeries.getTagValue(TagW.Thumbnail); if (thumb != null) { thumb.repaint(); } if (firstImageToDisplay) { boolean openNewTab = true; MediaSeriesGroup entry1 = dicomModel.getParent(dicomSeries, DicomModel.patient); if (entry1 != null) { synchronized (UIManager.VIEWER_PLUGINS) { for (final ViewerPlugin p : UIManager.VIEWER_PLUGINS) { if (entry1.equals(p.getGroupID())) { openNewTab = false; break; } } } } if (openNewTab) { SeriesViewerFactory plugin = UIManager.getViewerFactory(dicomSeries.getMimeType()); if (plugin != null && !(plugin instanceof MimeSystemAppFactory)) { ArrayList<MediaSeries> list = new ArrayList<MediaSeries>(1); list.add(dicomSeries); LoadSeries.openSequenceInPlugin(plugin, list, dicomModel, true); } } } } }); } // stateChanged(); } } // Increment progress bar in EDT and repaint when downloaded incrementProgressBarValue(); return true; } /** * @param inputStream * @param out * @param overrideList * @return bytes transferred. O = error, -1 = all bytes has been transferred, other = bytes transferred before * interruption */ public int writFile(InputStream inputStream, OutputStream out, int[] overrideList) { if (inputStream == null && out == null) { return 0; } DicomInputStream dis = null; DicomOutputStream dos = null; try { dis = new DicomInputStream(new BufferedInputStream(inputStream)); DicomObject dcm = dis.readDicomObject(); dos = new DicomOutputStream(new BufferedOutputStream(out)); if (overrideList != null) { MediaSeriesGroup study = dicomModel.getParent(dicomSeries, DicomModel.study); MediaSeriesGroup patient = dicomModel.getParent(dicomSeries, DicomModel.patient); VRMap vrMap = VRMap.getVRMap(); for (int tag : overrideList) { TagW tagElement = patient.getTagElement(tag); Object value = null; if (tagElement == null) { tagElement = study.getTagElement(tag); value = study.getTagValue(tagElement); } else { value = patient.getTagValue(tagElement); } if (value != null) { TagType type = tagElement.getType(); if (TagType.String.equals(type)) { dcm.putString(tag, vrMap.vrOf(tag), value.toString()); } else if (TagType.Date.equals(type) || TagType.Time.equals(type)) { dcm.putDate(tag, vrMap.vrOf(tag), (Date) value); } else if (TagType.Integer.equals(type)) { dcm.putInt(tag, vrMap.vrOf(tag), (Integer) value); } else if (TagType.Float.equals(type)) { dcm.putFloat(tag, vrMap.vrOf(tag), (Float) value); } } } } dos.writeDicomFile(dcm); return -1; } catch (InterruptedIOException e) { return e.bytesTransferred; } catch (IOException e) { e.printStackTrace(); return 0; } finally { FileUtil.safeClose(dos); FileUtil.safeClose(dis); } } } public synchronized DownloadPriority getPriority() { return priority; } public synchronized void setPriority(DownloadPriority priority) { this.priority = priority; } @Override public void setPriority() { DownloadPriority p = getPriority(); if (p != null) { if (StateValue.PENDING.equals(getState())) { boolean change = LoadRemoteDicomManifest.loadingQueue.remove(this); if (change) { p.setPriority(DownloadPriority.COUNTER.getAndDecrement()); LoadRemoteDicomManifest.loadingQueue.offer(this); synchronized (LoadRemoteDicomManifest.currentTasks) { for (LoadSeries s : LoadRemoteDicomManifest.currentTasks) { if (s != this && StateValue.STARTED.equals(s.getState())) { LoadSeries taskResume = new LoadSeries(s.getDicomSeries(), dicomModel, s.getProgressBar()); s.cancel(true); taskResume.setPriority(s.getPriority()); Thumbnail thumbnail = (Thumbnail) s.getDicomSeries().getTagValue(TagW.Thumbnail); if (thumbnail != null) { LoadSeries.removeAnonymousMouseAndKeyListener(thumbnail); addListenerToThumbnail(thumbnail, taskResume, dicomModel); } LoadRemoteDicomManifest.loadingQueue.offer(taskResume); LoadRemoteDicomManifest.addLoadSeries(taskResume, dicomModel); LoadRemoteDicomManifest.removeLoadSeries(s, dicomModel); break; } } } } } } } }
package org.xwiki.rendering.test.integration; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.Suite; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.xwiki.test.XWikiComponentInitializer; /** * Run all tests found in {@code *.test} files located in the classpath. These {@code *.test} files must follow the * conventions described in {@link org.xwiki.rendering.test.integration.TestDataParser}. * <p>Usage Example</p> * {@code * @RunWith(RenderingTestSuite.class) * public class IntegrationTests * { * } * } * <p>It's also possible to get access to the underlying Component Manager used, for example in order to register * Mock implementations of components. For example:</p> * {@code * @RunWith(RenderingTestSuite.class) * public class IntegrationTests * { * @RenderingTestSuite.Initialized * public void initialize(ComponentManager componentManager) * { * // Init mocks here for example * } * } * } * * @version $Id$ * @since 3.0RC1 */ public class RenderingTestSuite extends Suite { private static final TestDataGenerator GENERATOR = new TestDataGenerator(); private static final XWikiComponentInitializer INITIALIZER = new XWikiComponentInitializer(); private Class klass; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public static @interface Initialized { } private class TestClassRunnerForParameters extends BlockJUnit4ClassRunner { private final int parameterSetNumber; private final List<Object[]> parameterList; TestClassRunnerForParameters(Class<?> type, List<Object[]> parameterList, int i) throws InitializationError { super(type); this.parameterList = parameterList; this.parameterSetNumber = i; } /** * {@inheritDoc} */ @Override public Object createTest() throws Exception { return getTestClass().getOnlyConstructor().newInstance( computeParams()); } private Object[] computeParams() throws Exception { // Add the Component Manager as the last parameter in order to pass it to the Test constructor // Remove the first parameter which is the test name and that is not needed in RenderingTest Object[] originalObjects = this.parameterList.get(this.parameterSetNumber); Object[] newObjects = new Object[originalObjects.length]; System.arraycopy(originalObjects, 1, newObjects, 0, originalObjects.length - 1); newObjects[originalObjects.length - 1] = INITIALIZER.getComponentManager(); return newObjects; } /** * {@inheritDoc} */ @Override protected String getName() { return (String) this.parameterList.get(this.parameterSetNumber)[0]; } /** * {@inheritDoc} */ @Override protected String testName(final FrameworkMethod method) { return getName(); } /** * {@inheritDoc} */ @Override protected void validateConstructor(List<Throwable> errors) { validateOnlyOneConstructor(errors); } /** * {@inheritDoc} */ @Override protected Statement classBlock(RunNotifier notifier) { return childrenInvoker(notifier); } } private final ArrayList<Runner> runners = new ArrayList<Runner>(); /** * Only called reflectively. Do not use programmatically. */ public RenderingTestSuite(Class klass) throws Throwable { super(RenderingTest.class, Collections.<Runner>emptyList()); this.klass = klass; List<Object[]> parametersList = (List<Object[]>) GENERATOR.generateData(); for (int i = 0; i < parametersList.size(); i++) { this.runners.add(new TestClassRunnerForParameters(getTestClass().getJavaClass(), parametersList, i)); } } /** * {@inheritDoc} */ @Override protected List<Runner> getChildren() { return this.runners; } /** * {@inheritDoc} * * We override this method so that the JUnit results are not displayed in a test hierarchy with a single test * result for each node (as it would be otherwise since RenderingTest has a single test method). */ @Override public Description getDescription() { return Description.createSuiteDescription(getTestClass().getJavaClass()); } /** * {@inheritDoc} */ @Override public void run(RunNotifier notifier) { try { INITIALIZER.initializeConfigurationSource(); INITIALIZER.initializeExecution(); } catch (Exception e) { throw new RuntimeException("Failed to initialize Component Manager", e); } // Check all methods for a ComponentManager annotation and call the found ones. try { Object instance = this.klass.newInstance(); for (Method method : this.klass.getMethods()) { Annotation componentManagerAnnotation = method.getAnnotation(Initialized.class); if (componentManagerAnnotation != null) { // Call it! method.invoke(instance, INITIALIZER.getComponentManager()); } } } catch (Exception e) { throw new RuntimeException("Failed to call Component Manager initialization method", e); } try { super.run(notifier); } finally { try { INITIALIZER.shutdown(); } catch (Exception e) { throw new RuntimeException("Failed to shutdown Component Manager", e); } } } }
package org.opendaylight.yangtools.yang.data.impl; import static com.google.common.base.Preconditions.checkArgument; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Stack; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.Characters; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.opendaylight.yangtools.yang.data.api.ModifyAction; import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode; import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; /** * The XML Tree Builder is builder utility class designed to facilitate of * loading, reading and parsing XML documents into YANG DOM represented by * yang-data-api. <br> * The method {@link #buildDataTree(InputStream)} is designed to take and parse * XML as {@link InputStream}. The output of the operation SHOULD be root * <code>CompositeNode</code> or <code>SimpleElement</code> depends by which * element XML begins. The XML header is omitted by XML parser. * * @author Lukas Sedlak * * @see CompositeNode * @see SimpleNode * @see Node */ public final class XmlTreeBuilder { private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); private static XMLEventReader eventReader; private XmlTreeBuilder() { } /** * The method is designed to take and parse XML as {@link InputStream}. The * output of the operation SHOULD be root <code>CompositeNode</code> or * <code>SimpleElement</code> depends on element that XML document begins. * The XML header is omitted by XML parser. * * @param inputStream * XML Input Stream * @return root <code>Node</code> element conformant to XML start element in * most cases it will be CompositeNode which contains child Nodes * @throws XMLStreamException */ public static Node<?> buildDataTree(final InputStream inputStream) throws XMLStreamException { eventReader = xmlInputFactory.createXMLEventReader(inputStream); final Stack<Node<?>> processingQueue = new Stack<>(); Node<?> parentNode = null; Node<?> root = null; while (eventReader.hasNext()) { final XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { final StartElement startElement = event.asStartElement(); if (!processingQueue.isEmpty()) { parentNode = processingQueue.peek(); } CompositeNode compParentNode = null; if (parentNode instanceof CompositeNode) { compParentNode = (CompositeNode) parentNode; } Node<?> newNode = null; if (isCompositeNodeEvent(event)) { newNode = resolveCompositeNodeFromStartElement(startElement, compParentNode); } else if (isSimpleNodeEvent(event)) { newNode = resolveSimpleNodeFromStartElement(startElement, compParentNode); } if (newNode != null) { processingQueue.push(newNode); if (compParentNode != null) { compParentNode.getChildren().add(newNode); } } } else if (event.isEndElement()) { root = processingQueue.pop(); } } return root; } /** * Checks if the XMLEvent is compliant to SimpleNode tag that contains only * characters value. If the SimpleNode is composed only by empty XML tag * (i.e. {@code <emptyTag />} or {@code<emptyTag></emptyTag>}) the result * will be also <code>true</code>. * * @param event * actual XMLEvent that is processed * @return <code>true</code> only and only if the XMLEvent Start Element is * Simple element tag and contains character values or is empty XML * tag. * @throws XMLStreamException * * @see SimpleNode */ private static boolean isSimpleNodeEvent(final XMLEvent event) throws XMLStreamException { checkArgument(event != null, "XML Event cannot be NULL!"); if (event.isStartElement()) { if (eventReader.hasNext()) { final XMLEvent innerEvent; innerEvent = eventReader.peek(); if (innerEvent.isCharacters()) { final Characters chars = innerEvent.asCharacters(); if (!chars.isWhiteSpace()) { return true; } } else if (innerEvent.isEndElement()) { return true; } } } return false; } /** * Checks if XMLEvent is equivalent to CompositeNode Event. The * CompositeNode Event is XML element that conforms to the XML element that * contains 1..N XML child elements. (i.e. {@code <compositeNode> * <simpleNode>data</simpleNode> * </compositeNode>}) * * @param event * actual XMLEvent that is processed * @return <code>true</code> only if XML Element contains 1..N child * elements, otherwise returns <code>false</code> * @throws XMLStreamException * * @see CompositeNode */ private static boolean isCompositeNodeEvent(final XMLEvent event) throws XMLStreamException { checkArgument(event != null, "XML Event cannot be NULL!"); if (event.isStartElement()) { if (eventReader.hasNext()) { XMLEvent innerEvent; innerEvent = eventReader.peek(); if (innerEvent.isCharacters()) { Characters chars = innerEvent.asCharacters(); if (chars.isWhiteSpace()) { eventReader.nextEvent(); innerEvent = eventReader.peek(); } } if (innerEvent.isStartElement()) { return true; } } } return false; } /** * Creates and returns <code>SimpleNode</code> instance from actually * processed XML Start Element. * * @param startElement * actual XML Start Element that is processed * @param parent * Parent CompositeNode * @return <code>new SimpleNode</code> instance from actually processed XML * Start Element * @throws XMLStreamException * * @see SimpleNode */ private static SimpleNode<String> resolveSimpleNodeFromStartElement(final StartElement startElement, CompositeNode parent) throws XMLStreamException { checkArgument(startElement != null, "Start Element cannot be NULL!"); String data = null; if (eventReader.hasNext()) { final XMLEvent innerEvent = eventReader.peek(); if (innerEvent.isCharacters()) { final Characters chars = innerEvent.asCharacters(); if (!chars.isWhiteSpace()) { data = innerEvent.asCharacters().getData(); } } else if (innerEvent.isEndElement()) { data = ""; } } return NodeFactory.createImmutableSimpleNode(resolveElementQName(startElement), parent, data); } /** * Creates and returns <code>MutableCompositeNode</code> instance from * actually processed XML Start Element. * * @param startElement * actual XML Start Element that is processed * @param parent * Parent CompositeNode * @return <code>new MutableCompositeNode</code> instance from actually * processed XML Start Element * * @see CompositeNode * @see MutableCompositeNode */ private static CompositeNode resolveCompositeNodeFromStartElement(final StartElement startElement, CompositeNode parent) { checkArgument(startElement != null, "Start Element cannot be NULL!"); return NodeFactory.createMutableCompositeNode(resolveElementQName(startElement), parent, new ArrayList<Node<?>>(), ModifyAction.CREATE, null); } /** * Extract and retrieve XML Element QName to OpenDaylight QName. * * @param element * Start Element * @return QName instance composed of <code>elements</code> Namespace and * Local Part. * * @see QName */ private static QName resolveElementQName(final StartElement element) { checkArgument(element != null, "Start Element cannot be NULL!"); final String nsURI = element.getName().getNamespaceURI(); final String localName = element.getName().getLocalPart(); return new QName(URI.create(nsURI), localName); } }
package com.bottlerocketstudios.continuity; import android.os.SystemClock; import android.support.annotation.NonNull; import android.util.Log; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; public class ContinuityRepository { private final String TAG = ContinuityRepository.class.getSimpleName() + " " + this.hashCode(); public static final long DEFAULT_CHECK_INTERVAL_MS = 500; public static final long DEFAULT_IDLE_SHUTDOWN_MS = TimeUnit.SECONDS.toMillis(30); public static final long DEFAULT_LIFETIME_MS = TimeUnit.SECONDS.toMillis(2); public static final int DEFAULT_MAX_EMPTY_ITERATIONS = 10; private final long mCheckIntervalMs; private final long mIdleShutdownMs; private final long mDefaultLifetimeMs; private final int mMaxEmptyIterations; private final String mThreadLock = ""; private final Map<Object, List<ContinuityId>> mAnchoredContinuityIdMap = Collections.synchronizedMap(new WeakHashMap<Object, List<ContinuityId>>()); private final Map<ContinuityId, ContinuityContainer> mHeterogenousCache = Collections.synchronizedMap(new TreeMap<ContinuityId, ContinuityContainer>()); private final List<ContinuityId> mDeletionCandidates = new ArrayList<>(50); private final List<ContinuityId> mAnchoredContinuityIdList = new ArrayList<>(50); private CleanupThread mThread; /** * Create a ContinuityRepository using the default values */ public ContinuityRepository() { this(DEFAULT_CHECK_INTERVAL_MS, DEFAULT_IDLE_SHUTDOWN_MS, DEFAULT_LIFETIME_MS, DEFAULT_MAX_EMPTY_ITERATIONS); } /** * Create a ContinuityRepository with the provided settings. * * Several parameters can be adjusted to change how quickly cached items are released and how long * the watchdog thread that cleans the items will run while idle or empty. * * @param checkIntervalMs Time in milliseconds between checks to cleanup unused references. * @param idleShutdownMs Time in milliseconds before inactivity will release the Thread. * @param defaultLifetimeMs Default time in milliseconds to keep an un-anchored reference around. * @param maxEmptyIterations Number of checks to perform with an empty collection before releasing the Thread. */ public ContinuityRepository(long checkIntervalMs, long idleShutdownMs, long defaultLifetimeMs, int maxEmptyIterations) { mCheckIntervalMs = checkIntervalMs; mIdleShutdownMs = idleShutdownMs; mDefaultLifetimeMs = defaultLifetimeMs; mMaxEmptyIterations = maxEmptyIterations; } /** * Set from {@link Log#VERBOSE} to {@link Log#ERROR} to prevent logging anything below that level of importance. */ public void setMinLoggingLevel(int loggingLevel) { ContinuityLog.setMinLoggingLevel(loggingLevel); } /** * Thre primary interface for the ContinuityRepository. Use this method to construct or retrieve * a continuous object. * * @param anchor The object to anchor this instance to, it will remain available while this anchor is in memory. * @param continuousClass The class which you wish to make continuous across creation and destruction of anchor instances. * @param <T> The type of the continuous object. * @return A new or cached instance of the continuous object. You should always assume you are getting a cached instance. */ public <T> ContinuityBuilder<T> with(Object anchor, Class<T> continuousClass) { return new ContinuityBuilder<>(this, anchor, continuousClass, mDefaultLifetimeMs); } /** * Explicitly notify that this anchor is going out of scope so that references can be removed after lifetime timeout. */ public void onDestroy(Object anchor) { //Notify all of the ContinuousObjects associated with this anchor. notifyCacheOfDestruction(anchor); //Remove all anchored ContinuityIds associated with this anchor. mAnchoredContinuityIdMap.remove(anchor); touchCleanupThread(); } private void notifyCacheOfDestruction(Object anchor) { //First create a shallow copy of ids. List<ContinuityId> continuityIdList = new ArrayList<>(mAnchoredContinuityIdMap.get(anchor)); for (int i = 0; i < continuityIdList.size(); i++) { ContinuityContainer continuityContainer = mHeterogenousCache.get(continuityIdList.get(i)); //Ensure cache contains object if (continuityContainer != null) { //If it is a ContinuousObject, notify it of the destroyed anchor. Object object = continuityContainer.getObject(); if (object instanceof ContinuousObject) { ((ContinuousObject) object).onContinuityAnchorDestroyed(anchor); } } } } @SuppressWarnings("unchecked") <T> T get(Object anchor, ContinuityId continuityId, long lifetimeMs) { ContinuityContainer continuityContainer = mHeterogenousCache.get(continuityId); if (continuityContainer != null) { appendContinuityIdToAnchor(anchor, continuityId); continuityContainer.updateLifetimeMs(lifetimeMs); continuityContainer.setExpirationMs(0); touchCleanupThread(); return (T) continuityContainer.getObject(); } return null; } @SuppressWarnings("unchecked") <T> void put(ContinuityId continuityId, Object anchor, T instance, long lifetimeMs) { appendContinuityIdToAnchor(anchor, continuityId); mHeterogenousCache.put(continuityId, new ContinuityContainer(instance, lifetimeMs)); touchCleanupThread(); } void remove(ContinuityId continuityId) { mHeterogenousCache.remove(continuityId); touchCleanupThread(); } private void appendContinuityIdToAnchor(Object anchor, ContinuityId continuityId) { List<ContinuityId> continuityIdCollection = mAnchoredContinuityIdMap.get(anchor); if (continuityIdCollection == null) { continuityIdCollection = new ArrayList<>(); mAnchoredContinuityIdMap.put(anchor, continuityIdCollection); } continuityIdCollection.add(continuityId); } /** * This method will perform cleanup of any items that have lived past their lifetime without an anchor reference. */ private void performCleanup(CleanupThread cleanupThread) { /* * Check for error state of more than the known thread calling us. * This operation is not threadsafe because class fields are used to contain lists modified * during this operation. These fields are reused to reduce GC churn at the expense of thread safety. * * That isn't an issue because this method will only ever get called from the mThread loop. */ if (cleanupThread != mThread) { ContinuityLog.w(TAG, "Two threads were started"); cleanupThread.stopRunning(); return; } //Get the set of items that are in the cache which do not have anchors. //Reuse deletion candidate List to reduce GC churn on each iteration. mDeletionCandidates.clear(); mDeletionCandidates.addAll(mHeterogenousCache.keySet()); mDeletionCandidates.removeAll(getAnchoredContinuityIdCollection()); //Walk the set of unanchored values and either set their expiration time or delete expired items. //Use for instead of foreach to reduce GC churn on iterator creation/destruction. for (int i = 0; i < mDeletionCandidates.size(); i++) { ContinuityId continuityId = mDeletionCandidates.get(i); ContinuityContainer continuityContainer = mHeterogenousCache.get(continuityId); if (continuityContainer.getExpirationMs() > 0) { if (continuityContainer.getExpirationMs() < SystemClock.uptimeMillis()) { //Past deadline, delete it mHeterogenousCache.remove(continuityId); Object retainedObject = continuityContainer.getObject(); if (retainedObject instanceof ContinuousObject) { ((ContinuousObject) retainedObject).onContinuityDiscard(); } } } else { //Set expiration deadline. continuityContainer.setExpirationMs(SystemClock.uptimeMillis() + continuityContainer.getLifetimeMs()); } } } @NonNull private Collection<ContinuityId> getAnchoredContinuityIdCollection() { //Reuse anchored list to reduce GC churn. //Not thread safe. This is only called from performCleanup() which constrains it to a single thread. mAnchoredContinuityIdList.clear(); for (List<ContinuityId> continuityIdList: mAnchoredContinuityIdMap.values()) { mAnchoredContinuityIdList.addAll(continuityIdList); } return mAnchoredContinuityIdList; } boolean isEmpty() { return mHeterogenousCache.isEmpty(); } boolean isRunning() { return (mThread != null && mThread.isRunning()); } private void touchCleanupThread() { if (mThread == null) { ContinuityLog.v(TAG, "Cleanup thread was missing"); //Don't synchronize unless the thread is null. synchronized (mThreadLock) { //We block this section to ensure that only one instance is created. //Check that another thread didn't already create it while waiting on synchronize block. if (mThread == null) { mThread = createThread(); } } } mThread.touch(); } private CleanupThread createThread() { ContinuityLog.v(TAG, "Creating new cleanup thread"); CleanupThread thread = new CleanupThread(); thread.start(); return thread; } private void onThreadShutdown(CleanupThread cleanupThread) { if (mThread == cleanupThread) { ContinuityLog.v(TAG, "Removing thread reference"); mThread = null; } else { ContinuityLog.w(TAG, "An unexpected thread was shutdown"); } } private class CleanupThread extends Thread { private boolean mRunning; private long mLastTouchTimestampMs; private int mEmptyCount = 0; @Override public synchronized void start() { super.start(); mRunning = true; } @Override public void run() { ContinuityLog.v(TAG, "Running thread"); while (mRunning) { synchronized (this) { try { wait(mCheckIntervalMs); performCleanup(this); if (SystemClock.uptimeMillis() - mLastTouchTimestampMs > mIdleShutdownMs) { ContinuityLog.v(TAG, "Repository was idle too long."); stopRunning(); } if (isEmpty()) { mEmptyCount++; ContinuityLog.v(TAG, "Cache is empty."); if (mEmptyCount > mMaxEmptyIterations) { stopRunning(); } } else { mEmptyCount = 0; } } catch (InterruptedException e) { ContinuityLog.e(TAG, "Caught java.lang.InterruptedException", e); } } } ContinuityLog.v(TAG, "Shutting down thread"); onThreadShutdown(this); } public void touch() { mLastTouchTimestampMs = SystemClock.uptimeMillis(); if (!mRunning) start(); } public void stopRunning() { mRunning = false; } public boolean isRunning() { return mRunning; } } }
package org.waterforpeople.mapping.app.gwt.server.accesspoint; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointDto; import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointManagerService; import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointSearchCriteriaDto; import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointSummaryDto; import org.waterforpeople.mapping.app.gwt.client.accesspoint.TechnologyTypeDto; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import org.waterforpeople.mapping.domain.AccessPoint.Status; import org.waterforpeople.mapping.helper.AccessPointHelper; import services.S3Driver; import com.gallatinsystems.common.util.DateUtil; import com.gallatinsystems.image.GAEImageAdapter; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class AccessPointManagerServiceImpl extends RemoteServiceServlet implements AccessPointManagerService { @SuppressWarnings("unused") private static final Logger log = Logger .getLogger(AccessPointManagerService.class.getName()); private static final long serialVersionUID = 2710084399371519003L; @Override public List<AccessPointDto> listAccessPoints( AccessPointSearchCriteriaDto searchCriteria, Integer startRecord, Integer endRecord) { // TODO Auto-generated method stub return null; } @Override public List<AccessPointDto> listAllAccessPoints(Integer startRecord, Integer endRecord) { List<AccessPointDto> apDtoList = new ArrayList<AccessPointDto>(); AccessPointHelper ah = new AccessPointHelper(); for (AccessPoint apItem : ah.listAccessPoint()) { AccessPointDto apDto = copyCanonicalToDto(apItem); apDtoList.add(apDto); } return apDtoList; } private AccessPointDto copyCanonicalToDto(AccessPoint apCanonical) { AccessPointDto apDto = new AccessPointDto(); apDto.setKeyId(apCanonical.getKey().getId()); apDto.setAltitude(apCanonical.getAltitude()); apDto.setLatitude(apCanonical.getLatitude()); apDto.setLongitude(apCanonical.getLongitude()); apDto.setCommunityCode(apCanonical.getCommunityCode()); apDto.setCollectionDate(apCanonical.getCollectionDate()); apDto.setConstructionDate(apCanonical.getConstructionDate()); apDto.setCountryCode(apCanonical.getCountryCode()); apDto.setCostPer(apCanonical.getCostPer()); apDto.setCurrentManagementStructurePoint(apCanonical .getCurrentManagementStructurePoint()); apDto.setDescription(apCanonical.getDescription()); apDto.setFarthestHouseholdfromPoint(apCanonical .getFarthestHouseholdfromPoint()); apDto.setNumberOfHouseholdsUsingPoint(apCanonical .getNumberOfHouseholdsUsingPoint()); apDto.setPhotoURL(apCanonical.getPhotoURL()); apDto.setPointPhotoCaption(apCanonical.getPointPhotoCaption()); if (apCanonical.getCollectionDate() != null) { apDto.setYear(DateUtil.getYear(apCanonical.getCollectionDate())); } if (apCanonical.getPointStatus() == AccessPoint.Status.FUNCTIONING_HIGH) { apDto.setPointStatus(AccessPointDto.Status.FUNCTIONING_HIGH); } else if (apCanonical.getPointStatus() == AccessPoint.Status.FUNCTIONING_OK) { apDto.setPointStatus(AccessPointDto.Status.FUNCTIONING_OK); } else if (apCanonical.getPointStatus() == AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS) { apDto .setPointStatus(AccessPointDto.Status.FUNCTIONING_WITH_PROBLEMS); } else if (apCanonical.getPointStatus() == AccessPoint.Status.NO_IMPROVED_SYSTEM) { apDto.setPointStatus(AccessPointDto.Status.NO_IMPROVED_SYSTEM); } else { apDto.setPointStatus(AccessPointDto.Status.OTHER); apDto.setOtherStatus(apCanonical.getOtherStatus()); } if (apCanonical.getPointType() == AccessPointType.WATER_POINT) { apDto.setPointType(AccessPointDto.AccessPointType.WATER_POINT); } else { apDto.setPointType(AccessPointDto.AccessPointType.SANITATION_POINT); } return apDto; } private AccessPoint copyDtoToCanonical(AccessPointDto apDto) { AccessPoint accessPoint = new AccessPoint(); // Check to see if it is an update or insert if (apDto.getKeyId() != null) { Key key = KeyFactory.createKey(AccessPoint.class.getSimpleName(), apDto.getKeyId()); accessPoint.setKey(key); } accessPoint.setAltitude(apDto.getAltitude()); accessPoint.setLatitude(apDto.getLatitude()); accessPoint.setLongitude(apDto.getLongitude()); accessPoint.setCommunityCode(apDto.getCommunityCode()); accessPoint.setCollectionDate(apDto.getCollectionDate()); accessPoint.setConstructionDate(apDto.getConstructionDate()); accessPoint.setCostPer(apDto.getCostPer()); accessPoint.setCountryCode(apDto.getCountryCode()); accessPoint.setCurrentManagementStructurePoint(apDto .getCurrentManagementStructurePoint()); accessPoint.setDescription(apDto.getDescription()); accessPoint.setFarthestHouseholdfromPoint(apDto .getFarthestHouseholdfromPoint()); accessPoint.setNumberOfHouseholdsUsingPoint(apDto .getNumberOfHouseholdsUsingPoint()); accessPoint.setPhotoURL(apDto.getPhotoURL()); accessPoint.setPointPhotoCaption(apDto.getPointPhotoCaption()); if (apDto.getPointStatus() == AccessPointDto.Status.FUNCTIONING_HIGH) { accessPoint.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH); } else if (apDto.getPointStatus() == AccessPointDto.Status.FUNCTIONING_OK) { accessPoint.setPointStatus(AccessPoint.Status.FUNCTIONING_OK); } else if (apDto.getPointStatus() == AccessPointDto.Status.FUNCTIONING_WITH_PROBLEMS) { accessPoint .setPointStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS); } else if (apDto.getPointStatus() == AccessPointDto.Status.NO_IMPROVED_SYSTEM) { accessPoint.setPointStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM); } else { accessPoint.setPointStatus(AccessPoint.Status.OTHER); accessPoint.setOtherStatus(apDto.getOtherStatus()); } if (accessPoint.getPointStatus() == Status.OTHER) { accessPoint.setOtherStatus(apDto.getOtherStatus()); } if (apDto.getPointType() == AccessPointDto.AccessPointType.WATER_POINT) { accessPoint.setPointType(AccessPoint.AccessPointType.WATER_POINT); } else { accessPoint .setPointType(AccessPoint.AccessPointType.SANITATION_POINT); } return accessPoint; } @Override public Integer deleteAccessPoint(Long id) { // TODO Auto-generated method stub return null; } @Override public AccessPointDto getAccessPoint(Long id) { AccessPointHelper aph = new AccessPointHelper(); AccessPoint canonicalItem = aph.getAccessPoint(id); AccessPointDto apDto = copyCanonicalToDto(canonicalItem); return apDto; } @Override public AccessPointDto saveAccessPoint(AccessPointDto accessPointDto) { AccessPointHelper aph = new AccessPointHelper(); return copyCanonicalToDto(aph .saveAccessPoint(copyDtoToCanonical(accessPointDto))); } @Override public void delete(TechnologyTypeDto item) { // TODO Auto-generated method stub } @Override public TechnologyTypeDto getTechnologyType(Long id) { // TODO Auto-generated method stub return null; } @Override public List<TechnologyTypeDto> list() { // TODO Auto-generated method stub return null; } @Override public TechnologyTypeDto save(TechnologyTypeDto item) { // TODO Auto-generated method stub return null; } @Override public Boolean rotateImage(String fileName) { String imageURL = fileName.substring(fileName .indexOf("http://waterforpeople.s3.amazonaws.com/")); String bucket = "waterforpeople"; String rootURL = "http://waterforpeople.s3.amazonaws.com/"; Random rand = new Random(); String totalURL = imageURL + "?random=" + rand.nextInt(); InputStream in; ByteArrayOutputStream out = null; URL url; try { url = new URL(totalURL); in = url.openStream(); out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int size; while ((size = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, size); } } catch (IOException e) { log.log(Level.SEVERE, "Could not rotate image", e); } GAEImageAdapter gaeImg = new GAEImageAdapter(); byte[] newImage = gaeImg.rotateImage(out.toByteArray(), 90); S3Driver s3 = new S3Driver(); s3.uploadFile(bucket, imageURL, newImage); return null; /* * resp.getWriter() .print( "<html><body><img src=\"" + totalURL + * "\"/></body></html>"); */ // serve the first image // resp.setHeader("Cache-Control", // "no-store, no-cache, must-revalidate"); // resp.setContentType("image/jpeg"); // resp.getOutputStream().write(newImage); } /** * returns an array of AccessPointDto objects that match the criteria passed * in. */ public AccessPointDto[] listAccessPointByLocation(String country, String community, String type) { AccessPointDao apDAO = new AccessPointDao(); List<AccessPoint> summaries = apDAO.listAccessPointByLocation(country, community, type); AccessPointDto[] dtoList = null; if (summaries != null) { dtoList = new AccessPointDto[summaries.size()]; for (int i = 0; i < summaries.size(); i++) { AccessPointDto dto = copyCanonicalToDto(summaries.get(i)); dtoList[i] = dto; } } return dtoList; } }
package owltools.gaf.lego.server.handler; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.glassfish.jersey.server.JSONP; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import owltools.gaf.lego.MolecularModelJsonRenderer; import owltools.gaf.lego.MolecularModelManager; import owltools.gaf.lego.MolecularModelManager.OWLOperationResponse; import owltools.graph.OWLGraphWrapper; /** * Implementation of the {@link M3Handler}. Uses the build in function to render * generic object into JSON or JSONP.<br> * <br> * {@link Exception} are caught during the execution and reported in json * format. {@link Throwable} are not caught and will trigger a default error * page (and non standard status code for HTTP, i.e. 500). */ @Produces({MediaType.APPLICATION_JSON, "application/javascript"}) public class JsonOrJsonpModelHandler implements M3Handler { private static Logger LOG = Logger.getLogger(JsonOrJsonpModelHandler.class); static final String JSONP_DEFAULT_CALLBACK = "jsonp"; public static final String JSONP_DEFAULT_OVERWRITE = "json.wrf"; private final OWLGraphWrapper graph; private MolecularModelManager models = null; public JsonOrJsonpModelHandler(OWLGraphWrapper graph, MolecularModelManager models) { super(); this.graph = graph; this.models = models; } private synchronized MolecularModelManager getMolecularModelManager() throws OWLOntologyCreationException { if (models == null) { LOG.info("Creating m3 object"); models = new MolecularModelManager(graph); } return models; } /* * Builder: {"id": <id>, "instances": [...]} */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3GetModel(String modelId, boolean help) { if (help) { return helpMsg("fetches molecular model json"); } try { MolecularModelManager mmm = getMolecularModelManager(); return bulk(modelId, mmm, M3Response.INSTANTIATE); } catch (Exception exception) { return errorMsg("Could not retrieve model", exception); } } /* * Builder: {"id": <id>, "instances": [...]} */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3GenerateMolecularModel(String classId, String db, boolean help) { if (help) { return helpMsg("generates Minimal Model augmented with GO associations"); } try { System.out.println("db: " + db); System.out.println("cls: " + classId); MolecularModelManager mmm = getMolecularModelManager(); String mid = mmm.generateModel(classId, db); return bulk(mid, mmm, M3Response.INSTANTIATE); } catch (Exception exception) { return errorMsg("Could not generate model", exception); } } /* * Builder: {"id": <id>, "instances": [...]} */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3GenerateBlankMolecularModel(String db, boolean help) { if (help) { return helpMsg("generates Minimal Model augmented with GO associations"); } try { System.out.println("db: " + db); MolecularModelManager mmm = getMolecularModelManager(); String mid = mmm.generateBlankModel(db); return bulk(mid, mmm, M3Response.INSTANTIATE); } catch (Exception exception) { return errorMsg("Could not generate model", exception); } } /* * Info: {"message_type": "success", ..., "data: {"db": <db>}} */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3preloadGaf(String db, boolean help) { if (help) { return helpMsg("loads a GAF into memory (saves parsing time later on)"); } try { MolecularModelManager mmm = getMolecularModelManager(); mmm.loadGaf(db); return success(Collections.singletonMap("db", db), mmm); } catch (Exception exception) { return errorMsg("Could not preload gaf", exception); } } /* * Individiuals: [...] */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3CreateIndividual(String modelId, String classId, boolean help) { if (help) { return helpMsg("generates a new individual"); } try { MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.createIndividual(modelId, classId); return response(resp, mmm, null); } catch (Exception exception) { return errorMsg("Could not create individual in model", exception); } } @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3DeleteIndividual(String modelId, String individualId, boolean help) { if (help) { return helpMsg("delete the given individual"); } try { MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.deleteIndividual(modelId, individualId); return bulk(modelId, mmm, M3Response.INCONSISTENT); // TODO for now return the whole thing } catch (Exception exception) { return errorMsg("Could not create individual in model", exception); } } /* * Individiuals: [...] */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3AddType(String modelId, String individualId, String classId, boolean help) { if (help) { return helpMsg("generates ClassAssertion (named class)"); } try { MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.addType(modelId, individualId, classId); return response(resp, mmm, M3Response.MERGE); } catch (Exception exception) { return errorMsg("Could not add type to model", exception); } } /* * Individiuals: [...] */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3AddTypeExpression(String modelId, String individualId, String propertyId, String classId, boolean help) { if (help) { return helpMsg("generates ClassAssertion (anon class expression)"); } try { MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.addType(modelId, individualId, propertyId, classId); return response(resp, mmm, M3Response.MERGE); } catch (Exception exception) { return errorMsg("Could not add type expression to model", exception); } } /* * Individiuals: [...] */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3AddFact(String modelId, String propertyId, String individualId, String fillerId, boolean help) { if (help) { return helpMsg("generates ObjectPropertyAssertion"); } try { //System.out.println("mod: " + modelId); //System.out.println("fil: " + fillerId); //System.out.println("ind: " + individualId); //System.out.println("rel: " + propertyId); MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.addFact(modelId, propertyId, individualId, fillerId); M3Response response = response(resp, mmm, M3Response.MERGE); //printJsonResponse(response); return response; } catch (Exception exception) { return errorMsg("Could not add fact to model", exception); } } /* * Individiuals: [...] */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3RemoveFact(String propertyId, String modelId, String individualId, String fillerId, boolean help) { if (help) { return helpMsg("generates ObjectPropertyAssertion"); } try { System.out.println("mod: " + modelId); System.out.println("rel: " + propertyId); System.out.println("ind: " + individualId); System.out.println("fil: " + fillerId); MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.removeFact(modelId, propertyId, individualId, fillerId); return response(resp, mmm, M3Response.MERGE); } catch (Exception exception) { return errorMsg("Could not remove fact from model", exception); } } /* * Individiuals: [...] */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3CreateSimpleCompositeIndividual(String modelId, String classId, String enabledById, String occursInId, boolean help) { if (help) { return helpMsg("generates a new simple composite individual"); } try { System.out.println("mod: " + modelId); // necessatry System.out.println("act: " + classId); // necessatry System.out.println("enb: " + enabledById); // optional System.out.println("occ: " + occursInId); // optional // Create base instance, along with any simples optionals that are along for the ride. MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.addCompositeIndividual(modelId, classId, StringUtils.stripToNull(enabledById), StringUtils.stripToNull(occursInId)); return response(resp, mmm, M3Response.MERGE); } catch (Exception exception) { return errorMsg("Could not create individual in model", exception); } } /* * Other. */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3ExportModel(String modelId, boolean help) { if (help) { return helpMsg("Export the current content of the model"); } try { MolecularModelManager mmm = getMolecularModelManager(); String model = mmm.exportModel(modelId); return success(Collections.singletonMap("export", model), null); } catch (Exception exception) { return errorMsg("Could not export model", exception); } } /* * @see owltools.gaf.lego.server.handler.M3Handler#m3ImportModel */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3ImportModel(String model, boolean help) { if (help) { return helpMsg("Import the model into the server."); } try { MolecularModelManager mmm = getMolecularModelManager(); String modelId = mmm.importModel(model); return bulk(modelId, mmm, M3Response.INSTANTIATE); } catch (Exception exception) { return errorMsg("Could not import model", exception); } } /* * Return all meta-infomation about models in a format that the client can pick apart to help build an interface. * * @see owltools.gaf.lego.server.handler.M3Handler#m3GetAllModelIds(boolean) */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3GetAllModelIds(boolean help) { if (help) { return helpMsg("Get the current available model ids."); } try { // Get the different kinds of model IDs for the client. MolecularModelManager mmm = getMolecularModelManager(); Set<String> allModelIds = mmm.getAvailableModelIds(); //Set<String> scratchModelIds = mmm.getScratchModelIds(); //Set<String> storedModelIds = mmm.getStoredModelIds(); //Set<String> memoryModelIds = mmm.getCurrentModelIds(); Map<String, Object> map = new HashMap<String, Object>(); map.put("models_all", allModelIds); //map.put("models_memory", memoryModelIds); //map.put("models_stored", storedModelIds); //map.put("models_scratch", scratchModelIds); return information(map, mmm); } catch (Exception exception) { return errorMsg("Could not retrieve all available model ids", exception); } } /* * @see owltools.gaf.lego.server.handler.M3Handler#m3SaveModel */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response m3StoreModel(String modelId, boolean help) { if (help) { return helpMsg("Persist the given model on the server."); } try { MolecularModelManager mmm = getMolecularModelManager(); mmm.saveModel(modelId); M3Response response = new M3Response(M3Response.SUCCESS); response.message = "The model has been saved on the server."; return response; } catch (Exception exception) { return errorMsg("Could not save the model on the server.", exception); } } // END OF COMMANDS // Reworked calls for batch operations static class Request { String entity; String operation; Argument arguments; } static class Argument { String modelId; String subject; String object; String predicate; String individual; Expression[] expressions; Pair[] values; } static class Pair { String key; String value; } static class Expression { String type; String onProp; String literal; // Expression expression; } static class BatchResponse { } public BatchResponse call(Request[] requests) { return null; } /** * Get all relations/object properties (e.g. ro) * TODO provide this also in Batch mode * * @return response */ @Override @JSONP(callback = JSONP_DEFAULT_CALLBACK, queryParam = JSONP_DEFAULT_OVERWRITE) public M3Response getRelations() { /* * data: [{ * id: {String} * label: {String} * ?color: {String} // TODO in the future * ?glyph: {String} // TODO in the future * }] */ try { final MolecularModelManager mmm = getMolecularModelManager(); // retrieve (or load) all ontologies // put in a new wrapper OWLGraphWrapper wrapper = new OWLGraphWrapper(mmm.getOntology()); Collection<IRI> imports = mmm.getImports(); OWLOntologyManager manager = wrapper.getManager(); for (IRI iri : imports) { OWLOntology ontology = manager.loadOntology(iri); wrapper.addSupportOntology(ontology); } // get all properties from all loaded ontologies Set<OWLObjectProperty> properties = new HashSet<OWLObjectProperty>(); Set<OWLOntology> allOntologies = wrapper.getAllOntologies(); for(OWLOntology o : allOntologies) { properties.addAll(o.getObjectPropertiesInSignature()); } // retrieve id and label for all properties List<Map<String, String>> data = new ArrayList<Map<String,String>>(); for (OWLObjectProperty p : properties) { if (p.isBuiltIn()) { // skip owl:topObjectProperty continue; } String identifier = MolecularModelJsonRenderer.getId(p, wrapper); String label = wrapper.getLabel(p); Map<String, String> entry = new HashMap<String, String>(); entry.put("id", identifier); entry.put("label", label); data.add(entry); } // create response M3Response resp = new M3Response(M3Response.SUCCESS); resp.data = data; return resp ; } catch (OWLOntologyCreationException exception) { return errorMsg("Could not retrieve relations on the server.", exception); } } // END OF COMMANDS // UTIL private M3Response helpMsg(String msg) { M3Response response = new M3Response(M3Response.SUCCESS); response.message = msg; return response; } private M3Response warningMsg(String msg) { M3Response response = new M3Response(M3Response.WARNING); response.message = msg; return response; } private M3Response errorMsg(String msg, Exception e) { M3Response response = new M3Response(M3Response.ERROR); response.message = msg; if (e != null) { Map<String, Object> map = new HashMap<String, Object>(); map.put("exception", e.getClass().getName()); map.put("exceptionMsg", e.getMessage()); StringWriter stacktrace = new StringWriter(); e.printStackTrace(new PrintWriter(stacktrace)); map.put("exceptionTrace", stacktrace.toString()); response.commentary = map; } return response; } /** * @param data * @param mmm * @return REST response, never null */ private M3Response success(Object data, MolecularModelManager mmm) { M3Response response = new M3Response(M3Response.SUCCESS); response.data = data; if (mmm != null) { // TODO add consistent m3 model to result ? } return response; } /** * @param data * @param mmm * @return REST response, never null */ private M3Response information(Object data, MolecularModelManager mmm) { M3Response response = new M3Response(M3Response.INFORMATION); response.data = data; if (mmm != null) { // TODO add consistent m3 model to result ? } return response; } /** * @param modelId * @param mmm * @param respCat * @return REST response, never null */ private M3Response bulk(String modelId, MolecularModelManager mmm, String respCat) { M3Response response = new M3Response(respCat); if (mmm != null) { // TODO add consistent m3 model to result ? Map<Object, Object> obj = mmm.getModelObject(modelId); obj.put("id", modelId); response.data = obj; } return response; } /** * @param resp * @param mmm * @param intention * @return REST response, never null */ private M3Response response(OWLOperationResponse resp, MolecularModelManager mmm, String intention) { M3Response response; if (resp.isResultsInInconsistency()) { response = new M3Response(M3Response.INCONSISTENT); response.message = "unintentional inconsistency"; } else if ( ! resp.isSuccess()) { response = new M3Response(M3Response.ERROR); } else { //response = new M3Response(M3Response.SUCCESS); response = new M3Response(intention); } if (resp.getModelData() != null) { response.data = resp.getModelData(); } return response; } /** * Function for debugging: print JSON representation of a response to System.out. * * @param response */ static void printJsonResponse(M3Response response) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.create(); String json = gson.toJson(response); System.out.println("json: " + json); } }
package com.twitter.intellij.pants.util; import com.intellij.openapi.vfs.VirtualFile; import com.twitter.intellij.pants.base.PantsCodeInsightFixtureTestCase; import com.twitter.intellij.pants.util.PantsPsiUtil; import com.twitter.intellij.pants.util.Target; import java.util.ArrayList; import java.util.List; public class PantsPsiUtilTestBase extends PantsCodeInsightFixtureTestCase { private final String myPath; public PantsPsiUtilTestBase(String... path) { myPath = getPath(path); } @Override protected String getBasePath() { return myPath; } private static String getPath(String... args) { final StringBuilder result = new StringBuilder(); for (String folder : args) { result.append("/"); result.append(folder); } return result.toString(); } public void doTest(List<Target> actualTargets) { doTest(null, actualTargets); } public void doTest(String targetPath, List<Target> actualTargets) { final String buildPath = targetPath == null ? "BUILD" : targetPath + "/BUILD"; final VirtualFile buildFile = myFixture.copyFileToProject(getTestName(true) + ".py", buildPath); myFixture.configureFromExistingVirtualFile(buildFile); final List<Target> targets = PantsPsiUtil.findTargets(myFixture.getFile()); assertOrderedEquals(actualTargets, targets); } }
package ifc.frame; import lib.MultiMethodTest; import com.sun.star.frame.XTasksSupplier; /** * Testing <code>com.sun.star.frame.XTasksSupplier</code> * interface methods: * <ul> * <li><code> getActiveTask() </code></li> * <li><code> getTasks() </code></li> * </ul><p> * Test is <b> NOT </b> multithread compilant. <p> * @see com.sun.star.frame.XTasksSupplier */ public class _XTasksSupplier extends MultiMethodTest { public static XTasksSupplier oObj = null; /** * DEPRECATED. <p> * Has <b> OK </b> status . */ public void _getActiveTask() { // XTask active = oObj.getActiveTask() ; // if (active == null) // log.println("There is no active task"); // else // log.println("Active task: " + active.getName()); log.println("DEPRECATED"); tRes.tested("getActiveTask()", true) ; } // finished _getTasks() /** * DEPRECATED. <p> * Has <b> OK </b> status. */ public void _getTasks() { // int cnt = 0 ; // boolean result = true ; // XTask task = null ; // XEnumerationAccess enumAcc = oObj.getTasks() ; // XEnumeration enum = enumAcc.createEnumeration() ; // while (enum.hasMoreElements()) { // cnt ++ ; // try { // task = (XTask) enum.nextElement() ; // } catch (com.sun.star.container.NoSuchElementException e) { // e.printStackTrace(log); // } catch (com.sun.star.lang.WrappedTargetException e) { // e.printStackTrace(log); // if (task == null) // log.println("" + cnt + " task: null !!!") ; // else // log.println("" + cnt + " task: " + task.getName()) ; // result &= (task != null) ; // log.println("Totaly tasks: " + cnt) ; // if (cnt > 0 && result) tRes.tested("getTasks()", true) ; log.println("DEPRECATED"); tRes.tested("getTasks()", true); } // finished _removeResetListener() } // finished class _XTaskSupplier
package webserver; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import rabbit.Sender; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class WebServer { private final String CHARSET = StandardCharsets.UTF_8.name(); public WebServer() { this(8000); } public WebServer(int port) { HttpServer server = null; try { server = HttpServer.create(new InetSocketAddress(port), 0); } catch (IOException e) { e.printStackTrace(); } server.createContext("/job", new MyHandler()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("Server started and listening on port 8000. Example of request: /job?id=13&command=nmap%20info.uvt.ro"); } class MyHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException { String response; String paramQuery = t.getRequestURI().getQuery(); Map<String, String> params = queryToMap(paramQuery); String id = URLDecoder.decode(params.get("id"), CHARSET); String command = URLDecoder.decode(params.get("command"), CHARSET); if ((id != null) && (command != null)) { response = "Request valid, processing will start soon."; t.sendResponseHeaders(202, response.length()); Sender sender = new Sender(); sender.send(id, command); sender.closeConnection(); } else { response = "Request is invalid, id or command not present. Valid format could be: id=3&command=nmap%20info.uvt.ro"; t.sendResponseHeaders(400, response.length()); } OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } } private Map<String, String> queryToMap(String query){ Map<String, String> result = new HashMap<String, String>(); for (String param : query.split("&")) { String pair[] = param.split("="); if (pair.length>1) { result.put(pair[0], pair[1]); }else{ result.put(pair[0], ""); } } return result; } }
package com.ui.jcurses; import com.all.CurrentGameMessage; import com.all.GameMessage; import com.all.util.Pair; import com.frontend.GameMap; import com.frontend.GameMapEntry; import com.frontend.GameMapEntryColor; import com.frontend.UIMenuType; import com.frontend.UIState; import com.frontend.UserAction; import com.frontend.UIMenu; import com.ui.UI; import com.ui.UIMenuTypeComparator; import jcurses.system.*; import jcurses.widgets.*; import jcurses.util.*; import jcurses.event.*; import java.awt.Rectangle; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import jcurses.custom.*; public class JCursesUI extends Window implements UI { private CustomList messageList = null, currentMessageList= null; private final int MESSAGE_LIMIT = 5; private java.util.List<CustomButton> menuList; private Map<CustomButton,UIMenuType> buttonToMenuTypeMap = new HashMap<CustomButton,UIMenuType>(); CustomBorderPanel buttonPanel, gameMapPanel; //TextField inputField, tf_2, tf_3; private final static CharColor shortCutColor = new CharColor(CharColor.RED,CharColor.BLACK); private UIState uiState; private HashMap<Pair<Integer,Integer>,ModifiableLabel> coordLabelMap; private boolean uiInit; private static final Map<GameMapEntryColor, Short> COLOR_MAP = new HashMap<GameMapEntryColor,Short>(){{ put(GameMapEntryColor.BLUE, CharColor.BLUE); put(GameMapEntryColor.CYAN, CharColor.CYAN); put(GameMapEntryColor.GREEN, CharColor.GREEN); put(GameMapEntryColor.MAGENTA, CharColor.MAGENTA); put(GameMapEntryColor.RED, CharColor.RED); put(GameMapEntryColor.YELLOW, CharColor.YELLOW); put(GameMapEntryColor.WHITE, CharColor.WHITE); put(GameMapEntryColor.BLACK, CharColor.BLACK); }}; public JCursesUI(int width, int height){ super(width,height, true, "Game"); uiInit = false; coordLabelMap = new HashMap<Pair<Integer,Integer>,ModifiableLabel> (); GridLayoutManager mainWindowManager = new GridLayoutManager(10,10); getRootPanel().setLayoutManager(mainWindowManager); buttonPanel = new CustomBorderPanel(); messageList = new CustomList(MESSAGE_LIMIT); messageList.setTitle("Messages"); currentMessageList = new CustomList(MESSAGE_LIMIT); currentMessageList.setTitle("Current Message"); gameMapPanel = new CustomBorderPanel(80,20); //inputField = new TextField(5); mainWindowManager.addWidget(buttonPanel, 0,0,10,1, WidgetsConstants.ALIGNMENT_TOP, WidgetsConstants.ALIGNMENT_LEFT); mainWindowManager.addWidget(gameMapPanel, 0,1,5,9, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_CENTER); mainWindowManager.addWidget(currentMessageList, 5,1,5,3, WidgetsConstants.ALIGNMENT_TOP, WidgetsConstants.ALIGNMENT_LEFT); mainWindowManager.addWidget(messageList, 5,4,5,3, WidgetsConstants.ALIGNMENT_TOP, WidgetsConstants.ALIGNMENT_LEFT); //mainWindowManager.addWidget(inputField, 5,9,5,1, WidgetsConstants.ALIGNMENT_TOP, WidgetsConstants.ALIGNMENT_LEFT); this.pack(); this.show(); } @Override public void drawUIState() { if(!uiInit){ populateMenus(); populateMessageList(); populateCurrentMessage(); populateGameMap(); this.pack(); this.repaint(); uiInit = true; }else{ updateMenus(); updateMessageList(); updateCurrentMessage(); updateGameMap(); } } public void updateMenus(){ if(repopulateMenus()){ redrawMenus(); } } public void updateMessageList(){ if(repopulateMessageList()){ redrawMessageList(); } } public void updateCurrentMessage(){ if(repopulateCurrentMessage()){ redrawCurrentMessage(); } } public void updateGameMap(){ if(repopulateGameMap()){ redrawGameMap(); } } @Override public UserAction getUserAction() { // TODO Auto-generated method stub return null; } @Override public void setUIState(UIState uiState) { this.uiState = uiState; } private boolean repopulateCurrentMessage(){ populateCurrentMessage(); return true; } private void redrawCurrentMessage(){ currentMessageList.doRepaint(); } private void populateCurrentMessage() { CurrentGameMessage currentGameMessage = uiState.getCurrentGameMessage(); currentMessageList.clear(); for(String s : currentGameMessage.getMessageText().split(String.format("%s",System.getProperty("line.separator")))){ currentMessageList.add(s); } } private boolean repopulateMenus(){ populateMenus(); return true; } private void redrawMenus(){ buttonPanel.pack(); buttonPanel.doPaint(); } private void populateMenus(){ Map<UIMenuType,UIMenu> menuMap = uiState.getMenuMap(); menuList = new ArrayList<CustomButton>(); buttonToMenuTypeMap = new HashMap<CustomButton,UIMenuType>(); java.util.List<UIMenuType> availableMenuTypes = new ArrayList<UIMenuType>(menuMap.keySet()); Collections.sort(availableMenuTypes, new UIMenuTypeComparator()); for( UIMenuType umt : availableMenuTypes){ UIMenu val = menuMap.get(umt); if(val != null){ CustomButton b = new CustomButton(val.getName()); if(val.getHotkey() != null){ b.setShortCut(val.getHotkey()); //b.setShortCutColors(shortCutColor); } buttonToMenuTypeMap.put(b,umt); menuList.add(b); } } GridLayoutManager gm = new GridLayoutManager(menuList.size(),1); buttonPanel.setLayoutManager(gm); int i = 0; for(CustomButton b : menuList){ if(b != null){ gm.addWidget(b, i, 0, 1, 1,WidgetsConstants.ALIGNMENT_TOP,WidgetsConstants.ALIGNMENT_LEFT); i++; } } } private void redrawMessageList(){ messageList.doRepaint(); } private boolean repopulateMessageList(){ populateMessageList(); return true; } private void populateMessageList(){ java.util.List<GameMessage> lgm = uiState.getGameMessages(); messageList.clear(); int addedMessages=0; for(int i = lgm.size() - 1; i >= 0 ; i if(lgm.get(i) != null){ messageList.add(lgm.get(i).getMessageText()); addedMessages++; } if(addedMessages >= MESSAGE_LIMIT){ break; } } } private void redrawGameMap(){ for(ModifiableLabel ml : coordLabelMap.values()){ ml.doRepaint(); //repaint one by one to prevent flickering } } private boolean repopulateGameMap(){ GameMap gmap = uiState.getGameMap(); int mapHeight = gmap.getHeight(); int mapWidth = gmap.getWidth(); for(int row = 0 ; row < mapHeight ; row++){ for(int col = 0 ; col < mapWidth ; col++){ GameMapEntry gme = gmap.getObjectAt(row, col); Pair<Integer,Integer> coord = new Pair<Integer,Integer>(row,col); ModifiableLabel targetLabel = coordLabelMap.get(coord); if(targetLabel == null){ throw new IllegalStateException("Encountered unpopulated coordinate when updating game map"); } targetLabel.setString(Character.toString(gme.getSymbol())); targetLabel.setColors(new CharColor(COLOR_MAP.get(gme.getForegroundColor()),COLOR_MAP.get(gme.getBackgroundColor()))); } } return true; } private void populateGameMap(){ GameMap gmap = uiState.getGameMap(); int mapHeight = gmap.getHeight(); int mapWidth = gmap.getWidth(); DefaultLayoutManager gm = new DefaultLayoutManager(); gameMapPanel.setLayoutManager(gm); for(int row = 0 ; row < mapHeight ; row++){ for(int col = 0 ; col < mapWidth ; col++){ GameMapEntry gme = gmap.getObjectAt(row, col); ModifiableLabel l = new ModifiableLabel(Character.toString(gme.getSymbol()),new CharColor(COLOR_MAP.get(gme.getForegroundColor()),COLOR_MAP.get(gme.getBackgroundColor()))); gm.addWidget(l, col, row, 1, 1, WidgetsConstants.ALIGNMENT_CENTER, WidgetsConstants.ALIGNMENT_CENTER); Pair<Integer,Integer> p = new Pair<Integer, Integer>(row,col); coordLabelMap.put(p, l); } } } }
package eu.bcvsolutions.idm.acc.connector; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.UnknownHostException; import java.nio.file.Paths; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.MessageFormat; import java.time.ZoneId; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.UUID; import javax.naming.AuthenticationException; import javax.naming.CommunicationException; import javax.naming.Context; import javax.naming.NameAlreadyBoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.util.Strings; import org.identityconnectors.framework.common.exceptions.ConnectorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import eu.bcvsolutions.idm.acc.domain.AccResultCode; import eu.bcvsolutions.idm.acc.domain.ReconciliationMissingAccountActionType; import eu.bcvsolutions.idm.acc.domain.SynchronizationInactiveOwnerBehaviorType; import eu.bcvsolutions.idm.acc.domain.SynchronizationLinkedActionType; import eu.bcvsolutions.idm.acc.domain.SynchronizationMissingEntityActionType; import eu.bcvsolutions.idm.acc.domain.SynchronizationUnlinkedActionType; import eu.bcvsolutions.idm.acc.domain.SystemEntityType; import eu.bcvsolutions.idm.acc.domain.SystemOperationType; import eu.bcvsolutions.idm.acc.dto.AbstractSysSyncConfigDto; import eu.bcvsolutions.idm.acc.dto.ConnectorTypeDto; import eu.bcvsolutions.idm.acc.dto.SysConnectorKeyDto; import eu.bcvsolutions.idm.acc.dto.SysSchemaAttributeDto; import eu.bcvsolutions.idm.acc.dto.SysSchemaObjectClassDto; import eu.bcvsolutions.idm.acc.dto.SysSyncIdentityConfigDto; import eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto; import eu.bcvsolutions.idm.acc.dto.SysSystemDto; import eu.bcvsolutions.idm.acc.dto.SysSystemMappingDto; import eu.bcvsolutions.idm.acc.dto.filter.SysSchemaAttributeFilter; import eu.bcvsolutions.idm.acc.dto.filter.SysSyncConfigFilter; import eu.bcvsolutions.idm.acc.dto.filter.SysSystemMappingFilter; import eu.bcvsolutions.idm.acc.event.SystemMappingEvent; import eu.bcvsolutions.idm.acc.service.api.SysSchemaAttributeService; import eu.bcvsolutions.idm.acc.service.api.SysSyncConfigService; import eu.bcvsolutions.idm.acc.service.api.SysSystemAttributeMappingService; import eu.bcvsolutions.idm.acc.service.api.SysSystemMappingService; import eu.bcvsolutions.idm.core.api.domain.OperationState; import eu.bcvsolutions.idm.core.api.domain.Pair; import eu.bcvsolutions.idm.core.api.dto.AbstractDto; import eu.bcvsolutions.idm.core.api.dto.DefaultResultModel; import eu.bcvsolutions.idm.core.api.dto.IdmEntityStateDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto; import eu.bcvsolutions.idm.core.api.dto.OperationResultDto; import eu.bcvsolutions.idm.core.api.dto.ResultModel; import eu.bcvsolutions.idm.core.api.dto.filter.IdmEntityStateFilter; import eu.bcvsolutions.idm.core.api.exception.CoreException; import eu.bcvsolutions.idm.core.api.exception.ResultCodeException; import eu.bcvsolutions.idm.core.api.service.EntityStateManager; import eu.bcvsolutions.idm.core.api.service.IdmEntityStateService; import eu.bcvsolutions.idm.core.api.utils.CertificateUtils; import eu.bcvsolutions.idm.core.api.utils.SpinalCase; import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto; import eu.bcvsolutions.idm.core.eav.api.service.IdmFormAttributeService; import eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto; import eu.bcvsolutions.idm.core.ecm.api.service.AttachmentManager; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity_; import eu.bcvsolutions.idm.core.security.api.domain.GuardedString; import eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission; import eu.bcvsolutions.idm.ic.api.IcAttributeInfo; import eu.bcvsolutions.idm.ic.api.IcConnectorKey; import eu.bcvsolutions.idm.ic.api.IcObjectClassInfo; @Component(AdUserConnectorType.NAME) public class AdUserConnectorType extends DefaultConnectorType { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(AdUserConnectorType.class); // Connector type ID. public static final String NAME = "ad-connector-type"; public static final String USER_SEARCH_CONTAINER_KEY = "searchUserContainer"; public static final String NEW_USER_CONTAINER_KEY = "newUserContainer"; public static final String DELETE_USER_CONTAINER_KEY = "deleteUserContainer"; public static final String DOMAIN_KEY = "domainContainer"; public static final String LDAP_GROUPS_ATTRIBUTE = "ldapGroups"; public static final String HOST = "host"; public static final String PORT = "port"; public static final String USER = "user"; public static final String PASSWORD = "password"; public static final String SSL_SWITCH = "sslSwitch"; public static final String SYSTEM_NAME = "name"; public static final String STEP_ONE = "stepOne"; public static final String STEP_FOUR = "stepFour"; public static final String STEP_CREATE_USER_TEST = "stepCreateUserTest"; public static final String STEP_DELETE_USER_TEST = "stepDeleteUserTest"; public static final String STEP_ASSIGN_GROUP_TEST = "stepAssignToGroupTest"; public static final String TEST_CREATED_USER_DN_KEY = "testCreatedUserDN"; public static final String ENTITY_STATE_WITH_TEST_CREATED_USER_DN_KEY = "entityStateWithTestCreatedUserDN"; public static final String TEST_USERNAME_KEY = "testUserName"; public static final String TEST_USER_CONTAINER_KEY = "userContainer"; public static final String TEST_GROUP_KEY = "testGroup"; public static final String PAIRING_SYNC_SWITCH_KEY = "pairingSyncSwitch"; public static final String PROTECTED_MODE_SWITCH_KEY = "protectedModeSwitch"; public static final String PAIRING_SYNC_ID = "pairingSyncId"; private static final String SSL = "ssl"; private static final String PRINCIPAL = "principal"; private static final String CREDENTIALS = "credentials"; private static final String SCHEMA_ID_KEY = "schemaId"; private static final String CRT_ATTACHMENT_ID_KEY = "attachmentId"; private static final String CRT_SUBJECT_DN_KEY = "subjectDN"; private static final String CRT_FINGER_PRINT_KEY = "fingerPrint"; private static final String CRT_VALIDITY_FROM_KEY = "crtValidityFrom"; private static final String CRT_VALIDITY_TILL_KEY = "crtValidityTill"; private static final String CRT_FILE_PATH_KEY = "crtFilePath"; private static final String SERVER_CRT_ATTACHMENT_ID_KEY = "serverAttachmentId"; private static final String SERVER_CRT_SUBJECT_DN_KEY = "serverSubjectDN"; private static final String SERVER_CRT_FINGER_PRINT_KEY = "serverFingerPrint"; private static final String SERVER_CRT_VALIDITY_FROM_KEY = "serverCrtValidityFrom"; private static final String SERVER_CRT_VALIDITY_TILL_KEY = "serverCrtValidityTill"; private static final String HAS_TRUSTED_CA_KEY = "hasTrustedCa"; private static final String ENTRY_OBJECT_CLASSES_KEY = "accountObjectClasses"; private static final String OBJECT_CLASSES_TO_SYNC_KEY = "objectClassesToSynchronize"; private static final String VLV_SORT_ATTRIBUTE_KEY = "vlvSortAttribute"; private static final String USE_VLV_SORT_KEY = "useVlvControls"; private static final String PAGE_SIZE_KEY = "pageSize"; private static final String DEFAULT_UID_KEY = "defaultIdAttribute"; private static final String BASE_CONTEXT_USER_KEY = "userBaseContexts"; private static final String ROOT_SUFFIXES_KEY = "baseContextsToSynchronize"; private static final String PAIRING_SYNC_DN_ATTR_KEY = "pairingSyncEavDnAttribute"; private static final String MAPPING_SYNC_ID = "mappingSyncId"; // Default values private static final String[] ENTRY_OBJECT_CLASSES_DEFAULT_VALUES = {"top", "user", "person", "organizationalPerson"}; public static final String SAM_ACCOUNT_NAME_ATTRIBUTE = "sAMAccountName"; public static final String PAIRING_SYNC_DN_ATTR_DEFAULT_VALUE = "distinguishedName"; private static final int PAGE_SIZE_DEFAULT_VALUE = 100; private static final String PAIRING_SYNC_NAME = "Pairing sync"; @Autowired private AttachmentManager attachmentManager; @Autowired private EntityStateManager entityStateManager; @Autowired private IdmEntityStateService entityStateService; @Autowired private SysSystemMappingService systemMappingService; @Autowired private SysSystemAttributeMappingService systemAttributeMappingService; @Autowired private SysSyncConfigService syncConfigService; @Autowired private SysSchemaAttributeService schemaAttributeService; @Autowired private IdmFormAttributeService formAttributeService; @Override public String getConnectorName() { return "net.tirasa.connid.bundles.ad.ADConnector"; } @Override public String getIconKey() { return "ad-connector-icon"; } @Override public Map<String, String> getMetadata() { // Default values: Map<String, String> metadata = super.getMetadata(); metadata.put(SYSTEM_NAME, this.findUniqueSystemName("MS AD - Users", 1)); metadata.put(PORT, "636"); metadata.put(PAIRING_SYNC_DN_ATTR_KEY, PAIRING_SYNC_DN_ATTR_DEFAULT_VALUE); metadata.put(PROTECTED_MODE_SWITCH_KEY, "false"); return metadata; } @Override public ConnectorTypeDto load(ConnectorTypeDto connectorType) { super.load(connectorType); if (!connectorType.isReopened()) { return connectorType; } // Load the system. SysSystemDto systemDto = (SysSystemDto) connectorType.getEmbedded().get(SYSTEM_DTO_KEY); Assert.notNull(systemDto, "System must exists!"); connectorType.getMetadata().put(SYSTEM_NAME, systemDto.getName()); Map<String, String> metadata = connectorType.getMetadata(); IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto); // Find attribute with port. metadata.put(PORT, getValueFromConnectorInstance(PORT, systemDto, connectorFormDef)); // Find attribute with host. metadata.put(HOST, getValueFromConnectorInstance(HOST, systemDto, connectorFormDef)); // Find attribute with user. metadata.put(USER, getValueFromConnectorInstance(PRINCIPAL, systemDto, connectorFormDef)); // Find attribute with ssl switch. metadata.put(SSL_SWITCH, getValueFromConnectorInstance(SSL, systemDto, connectorFormDef)); IdmFormDefinitionDto operationOptionsFormDefinition = this.getSystemService().getOperationOptionsConnectorFormDefinition(systemDto); if (operationOptionsFormDefinition != null) { // Find attribute with domain. metadata.put(DOMAIN_KEY, getValueFromConnectorInstance(DOMAIN_KEY, systemDto, operationOptionsFormDefinition)); // Find attribute with container with existed users. metadata.put(USER_SEARCH_CONTAINER_KEY, getValueFromConnectorInstance(USER_SEARCH_CONTAINER_KEY, systemDto, operationOptionsFormDefinition)); // Find attribute with container with new users. metadata.put(NEW_USER_CONTAINER_KEY, getValueFromConnectorInstance(NEW_USER_CONTAINER_KEY, systemDto, operationOptionsFormDefinition)); // Find attribute with container with deleted users. metadata.put(DELETE_USER_CONTAINER_KEY, getValueFromConnectorInstance(DELETE_USER_CONTAINER_KEY, systemDto, operationOptionsFormDefinition)); } // Load the provisioning mapping. SysSystemMappingFilter mappingFilter = new SysSystemMappingFilter(); mappingFilter.setSystemId(systemDto.getId()); mappingFilter.setOperationType(SystemOperationType.PROVISIONING); SysSystemMappingDto mappingDto = systemMappingService.find(mappingFilter, null) .getContent() .stream().min(Comparator.comparing(SysSystemMappingDto::getCreated)) .orElse(null); if (mappingDto != null) { connectorType.getEmbedded().put(DefaultConnectorType.MAPPING_DTO_KEY, mappingDto); connectorType.getMetadata().put(MAPPING_ID, mappingDto.getId().toString()); connectorType.getMetadata().put(PROTECTED_MODE_SWITCH_KEY, String.valueOf(mappingDto.isProtectionEnabled())); } // Load the sync mapping. SysSystemMappingFilter syncMappingFilter = new SysSystemMappingFilter(); syncMappingFilter.setSystemId(systemDto.getId()); syncMappingFilter.setOperationType(SystemOperationType.SYNCHRONIZATION); SysSystemMappingDto syncMappingDto = systemMappingService.find(syncMappingFilter, null) .getContent() .stream().min(Comparator.comparing(SysSystemMappingDto::getCreated)) .orElse(null); if (syncMappingDto != null) { connectorType.getMetadata().put(MAPPING_SYNC_ID, syncMappingDto.getId().toString()); } // Load the pairing sync (beware by name!). SysSyncConfigFilter syncFilter = new SysSyncConfigFilter(); syncFilter.setSystemId(systemDto.getId()); syncFilter.setName(PAIRING_SYNC_NAME); AbstractSysSyncConfigDto syncDto = syncConfigService.find(syncFilter, null) .getContent() .stream().min(Comparator.comparing(AbstractDto::getCreated)) .orElse(null); if (syncDto != null) { connectorType.getMetadata().put(PAIRING_SYNC_ID, syncDto.getId().toString()); } IdmEntityStateFilter entityStateFilter = new IdmEntityStateFilter(); entityStateFilter.setOwnerId(systemDto.getId()); entityStateFilter.setOwnerType(entityStateManager.getOwnerType(systemDto.getClass())); entityStateFilter.setResultCode(AccResultCode.WIZARD_AD_CREATED_TEST_USER_DN.getCode()); IdmEntityStateDto entityStateDto = entityStateManager.findStates(entityStateFilter, null).stream().findFirst().orElse(null); Object dn = null; if (entityStateDto != null && entityStateDto.getResult() != null && entityStateDto.getResult().getModel() != null && entityStateDto.getResult().getModel().getParameters() != null) { dn = entityStateDto.getResult().getModel().getParameters().get(TEST_CREATED_USER_DN_KEY); } if (dn instanceof String) { String testUserDN = (String) dn; connectorType.getMetadata().put(ENTITY_STATE_WITH_TEST_CREATED_USER_DN_KEY, entityStateDto.getId().toString()); connectorType.getMetadata().put(TEST_CREATED_USER_DN_KEY, testUserDN); } return connectorType; } @Override @Transactional public ConnectorTypeDto execute(ConnectorTypeDto connectorType) { try { super.execute(connectorType); if (STEP_ONE.equals(connectorType.getWizardStepName())) { executeStepOne(connectorType); } else if (STEP_CREATE_USER_TEST.equals(connectorType.getWizardStepName())) { executeCreateUserTest(connectorType); } else if (STEP_DELETE_USER_TEST.equals(connectorType.getWizardStepName())) { executeDeleteUserTest(connectorType); } else if (STEP_ASSIGN_GROUP_TEST.equals(connectorType.getWizardStepName())) { executeAssignTestUserToGroup(connectorType); } else if (STEP_FOUR.equals(connectorType.getWizardStepName())) { executeStepFour(connectorType); } else { // Default loading of system DTO. String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY); Assert.notNull(systemId, "System ID cannot be null!"); SysSystemDto systemDto = this.getSystemService().get(systemId); connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto); } } catch (ResultCodeException ex) { if (ex.getCause() instanceof AuthenticationException) { throw new ResultCodeException(AccResultCode.WIZARD_AD_AUTHENTICATION_FAILED, ex.getCause()); } if (ex.getCause() instanceof CommunicationException) { CommunicationException exCause = (CommunicationException) ex.getCause(); if (exCause.getRootCause() instanceof UnknownHostException) { UnknownHostException rootCause = (UnknownHostException) exCause.getRootCause(); throw new ResultCodeException(AccResultCode.WIZARD_AD_UNKNOWN_HOST, ImmutableMap.of("host", rootCause.getLocalizedMessage()), ex.getCause()); } } throw ex; } return connectorType; } /** * Execute first step of AD wizard. */ private void executeStepOne(ConnectorTypeDto connectorType) { String port = connectorType.getMetadata().get(PORT); Assert.notNull(port, "Port cannot be null!"); String host = connectorType.getMetadata().get(HOST); Assert.notNull(host, "Host cannot be null!"); String user = connectorType.getMetadata().get(USER); Assert.notNull(user, "Username cannot be null!"); String sslSwitch = connectorType.getMetadata().get(SSL_SWITCH); Assert.notNull(sslSwitch, "SSL switch cannot be null!"); String password = connectorType.getMetadata().get(PASSWORD); String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY); SysSystemDto systemDto; boolean create = true; if (systemId != null) { // System already exists. create = false; systemDto = getSystemService().get(UUID.fromString(systemId), IdmBasePermission.READ); } else { // Create new system. systemDto = new SysSystemDto(); // System is set as readOnly only if is new. systemDto.setReadonly(true); } systemDto.setName(connectorType.getMetadata().get(SYSTEM_NAME)); // Resolve remote system. systemDto.setRemoteServer(connectorType.getRemoteServer()); // Find connector key and set it to the system. IcConnectorKey connectorKey = getConnectorManager().findConnectorKey(connectorType); Assert.notNull(connectorKey, "Connector key was not found!"); systemDto.setConnectorKey(new SysConnectorKeyDto(connectorKey)); systemDto = getSystemService().save(systemDto, create ? IdmBasePermission.CREATE : IdmBasePermission.UPDATE); // Put new system to the connector type (will be returned to FE). connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto); IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto); // Set the port. this.setValueToConnectorInstance(PORT, port, systemDto, connectorFormDef); // Set the host. this.setValueToConnectorInstance(HOST, host, systemDto, connectorFormDef); // Set the user. this.setValueToConnectorInstance(PRINCIPAL, user, systemDto, connectorFormDef); // Set the SSL switch. this.setValueToConnectorInstance(SSL, sslSwitch, systemDto, connectorFormDef); // Set the password. // Password is mandatory only if none exists in connector configuration. String passwordInSystem = this.getValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef); if (Strings.isNotBlank(password) && !GuardedString.SECRED_PROXY_STRING.equals(password)) { this.setValueToConnectorInstance(CREDENTIALS, password, systemDto, connectorFormDef); } else { Assert.notNull(passwordInSystem, "Password cannot be null!"); // Load from confidential storage. password = getConfidentialValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef); } // Find domain DN. if (Strings.isBlank(connectorType.getMetadata().get(DOMAIN_KEY))) { String defaultNamingContext = this.findDnsHostName("389", host, user, password, false); connectorType.getMetadata().put(DOMAIN_KEY, defaultNamingContext); } // Find Users container DN. String usersContainerDN = this.findDn("(&(CN=Users)(objectClass=container))", "389", host, user, password, false); connectorType.getMetadata().put(TEST_USER_CONTAINER_KEY, usersContainerDN); // Find Domain Users group DN. String domainUsersDN = this.findDn("(&(CN=Domain Guests)(objectClass=group))", "389", host, user, password, false); connectorType.getMetadata().put(TEST_GROUP_KEY, domainUsersDN); // Generate random test user name. connectorType.getMetadata().put(TEST_USERNAME_KEY, MessageFormat.format("TestUserIdM_{0}", UUID.randomUUID().toString().substring(0, 8)) ); if (!Boolean.parseBoolean(sslSwitch)) { // LDAPS is trun off, this step will be skipped. return; } Pair<X509Certificate, Boolean> serverCertificatePair = getServerCertificate(port, host); if (serverCertificatePair != null) { boolean hasTrustedCA = serverCertificatePair.getValue(); // Put information if the server already has trusted certificate. connectorType.getMetadata().put(HAS_TRUSTED_CA_KEY, String.valueOf(hasTrustedCA)); X509Certificate serverCertificate = serverCertificatePair.getKey(); X509Certificate resultCertificate = getCertificateFromAD(serverCertificate, port, host, user, password); if (resultCertificate != null) { try { // Save CA as file. File caFile = new File(Paths.get(getTrustedCaFolder(), getCaFileName(resultCertificate)).toString()); FileUtils.copyInputStreamToFile(CertificateUtils.certificateToPem(resultCertificate), caFile); // Save certificate as a temporary attachment. IdmAttachmentDto attachment = new IdmAttachmentDto(); attachment.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE); attachment.setName("AD_CA"); attachment.setMimetype("application/x-pem-file"); attachment.setInputData(CertificateUtils.certificateToPem(resultCertificate)); attachment = attachmentManager.saveAttachment(null, attachment); // Save server certificate as a temporary attachment. IdmAttachmentDto serverAttachment = new IdmAttachmentDto(); serverAttachment.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE); serverAttachment.setName("SERVER_AD_CA"); serverAttachment.setMimetype("application/x-pem-file"); serverAttachment.setInputData(CertificateUtils.certificateToPem(serverCertificate)); serverAttachment = attachmentManager.saveAttachment(null, serverAttachment); // Put data to connectorType for FE connectorType.getMetadata().put(CRT_ATTACHMENT_ID_KEY, attachment.getId().toString()); connectorType.getMetadata().put(CRT_SUBJECT_DN_KEY, resultCertificate.getSubjectDN().getName()); connectorType.getMetadata().put(CRT_VALIDITY_FROM_KEY, getZonedDateTime(resultCertificate.getNotBefore())); connectorType.getMetadata().put(CRT_VALIDITY_TILL_KEY, getZonedDateTime(resultCertificate.getNotAfter())); // Fingerprint by SHA1 (is use in windows certificate manager) connectorType.getMetadata().put(CRT_FINGER_PRINT_KEY, DigestUtils.sha1Hex(resultCertificate.getEncoded())); connectorType.getMetadata().put(CRT_FILE_PATH_KEY, Paths.get(caFile.getAbsolutePath()).toString()); // Put data to connectorType for FE connectorType.getMetadata().put(SERVER_CRT_ATTACHMENT_ID_KEY, serverAttachment.getId().toString()); connectorType.getMetadata().put(SERVER_CRT_SUBJECT_DN_KEY, serverCertificate.getSubjectDN().getName()); connectorType.getMetadata().put(SERVER_CRT_VALIDITY_FROM_KEY, getZonedDateTime(serverCertificate.getNotBefore())); connectorType.getMetadata().put(SERVER_CRT_VALIDITY_TILL_KEY, getZonedDateTime(serverCertificate.getNotAfter())); // Fingerprint by SHA1 (is use in windows certificate manager) connectorType.getMetadata().put(SERVER_CRT_FINGER_PRINT_KEY, DigestUtils.sha1Hex(serverCertificate.getEncoded())); } catch (CertificateException | IOException ex) { throw new CoreException(ex.getLocalizedMessage(), ex); } } } } private void executeCreateUserTest(ConnectorTypeDto connectorType) { String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY); Assert.notNull(systemId, "System ID cannot be null!"); SysSystemDto systemDto = this.getSystemService().get(systemId); connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto); IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto); String port = getValueFromConnectorInstance(PORT, systemDto, connectorFormDef); String host = getValueFromConnectorInstance(HOST, systemDto, connectorFormDef); String user = getValueFromConnectorInstance(PRINCIPAL, systemDto, connectorFormDef); boolean ssl = Boolean.parseBoolean(getValueFromConnectorInstance(SSL, systemDto, connectorFormDef)); String password = getConfidentialValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef); String testUser = connectorType.getMetadata().get(TEST_USERNAME_KEY); Assert.notNull(testUser, "Test username cannot be null!"); String usersContainer = connectorType.getMetadata().get(TEST_USER_CONTAINER_KEY); Assert.notNull(usersContainer, "Test user container cannot be null!"); // Check exist of container on the AD. String usersContainerDN = this.findDn( MessageFormat.format("(&(distinguishedName={0})(|(objectClass=container)(objectClass=organizationalUnit)))", usersContainer) , port, host, user, password, ssl); if (Strings.isBlank(usersContainerDN)) { throw new ResultCodeException(AccResultCode.WIZARD_AD_CONTAINER_NOT_FOUND, ImmutableMap.of("dn", usersContainer ) ); } String createdUserDN = createTestUser(testUser, usersContainerDN, port, host, user, password, ssl); // As protection against unauthorized deletion of a user other than the one // created, the DN on the BE will be in the entity state. IdmEntityStateDto entityStateWithTestUser = createEntityStateWithTestUser(systemDto, createdUserDN); connectorType.getMetadata().put(ENTITY_STATE_WITH_TEST_CREATED_USER_DN_KEY, entityStateWithTestUser.getId().toString()); connectorType.getMetadata().put(TEST_CREATED_USER_DN_KEY, createdUserDN); } private void executeAssignTestUserToGroup(ConnectorTypeDto connectorType) { String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY); Assert.notNull(systemId, "System ID cannot be null!"); SysSystemDto systemDto = this.getSystemService().get(systemId); connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto); IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto); String port = getValueFromConnectorInstance(PORT, systemDto, connectorFormDef); String host = getValueFromConnectorInstance(HOST, systemDto, connectorFormDef); String user = getValueFromConnectorInstance(PRINCIPAL, systemDto, connectorFormDef); boolean ssl = Boolean.parseBoolean(getValueFromConnectorInstance(SSL, systemDto, connectorFormDef)); String password = getConfidentialValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef); String testUser = connectorType.getMetadata().get(TEST_USERNAME_KEY); Assert.notNull(testUser, "Test username cannot be null!"); String entityStateId = connectorType.getMetadata().get(ENTITY_STATE_WITH_TEST_CREATED_USER_DN_KEY); Assert.notNull(entityStateId, "Entity state ID with created test user DN cannot be null!"); // Find Domain Users group DN. String groupDN = this.findDn("(&(CN=Domain Guests)(objectClass=group))", port, host, user, password, ssl); if (Strings.isBlank(groupDN)) { throw new ResultCodeException(AccResultCode.WIZARD_AD_GROUP_NOT_FOUND, ImmutableMap.of("dn", groupDN ) ); } // As protection against unauthorized deletion of a user other than the one // created, the DN will be loaded from the entity state. IdmEntityStateDto entityStateDto = entityStateService.get(entityStateId); Assert.notNull(entityStateDto, "Entity state with created test user DN cannot be null!"); ResultModel model = entityStateDto.getResult().getModel(); Object dn = model.getParameters().get(TEST_CREATED_USER_DN_KEY); Assert.isTrue(dn instanceof String, "Test domain users cannot be null!"); String testUserDN = (String) dn; // Assign test user to the group. assignTestUserToGroup(testUserDN, groupDN, port, host, user, password, ssl); } private void executeDeleteUserTest(ConnectorTypeDto connectorType) { String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY); Assert.notNull(systemId, "System ID cannot be null!"); SysSystemDto systemDto = this.getSystemService().get(systemId); connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto); IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto); String port = getValueFromConnectorInstance(PORT, systemDto, connectorFormDef); String host = getValueFromConnectorInstance(HOST, systemDto, connectorFormDef); String user = getValueFromConnectorInstance(PRINCIPAL, systemDto, connectorFormDef); boolean ssl = Boolean.parseBoolean(getValueFromConnectorInstance(SSL, systemDto, connectorFormDef)); String password = getConfidentialValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef); String entityStateId = connectorType.getMetadata().get(ENTITY_STATE_WITH_TEST_CREATED_USER_DN_KEY); Assert.notNull(entityStateId, "Entity state ID with created test user DN cannot be null!"); // As protection against unauthorized deletion of a user other than the one // created, the DN will be loaded from the entity state. IdmEntityStateDto entityStateDto = entityStateService.get(entityStateId); Assert.notNull(entityStateDto, "Entity state with created test user DN cannot be null!"); ResultModel model = entityStateDto.getResult().getModel(); Object dn = model.getParameters().get(TEST_CREATED_USER_DN_KEY); Assert.isTrue(dn instanceof String, "Test domain users cannot be null!"); String testDomainUsers = (String) dn; // Delete test user from AD. deleteTestUser(testDomainUsers, port, host, user, password, ssl); // Delete entity state. entityStateService.delete(entityStateDto); } /** * Step for filling additional information as connector (OU) DNs. Enable protected mode. Add pairing sync. */ private void executeStepFour(ConnectorTypeDto connectorType) { String systemId = connectorType.getMetadata().get(SYSTEM_DTO_KEY); String pairingSyncId = connectorType.getMetadata().get(PAIRING_SYNC_ID); Assert.notNull(systemId, "System ID cannot be null!"); SysSystemDto systemDto = this.getSystemService().get(systemId); connectorType.getEmbedded().put(SYSTEM_DTO_KEY, systemDto); boolean pairingSyncSwitch = Boolean.parseBoolean(connectorType.getMetadata().get(PAIRING_SYNC_SWITCH_KEY)); String pairingSyncAttributeCode = connectorType.getMetadata().get(PAIRING_SYNC_DN_ATTR_KEY); if (pairingSyncAttributeCode == null) { pairingSyncAttributeCode = PAIRING_SYNC_DN_ATTR_DEFAULT_VALUE; } boolean protectedModeSwitch = Boolean.parseBoolean(connectorType.getMetadata().get(PROTECTED_MODE_SWITCH_KEY)); IdmFormDefinitionDto connectorFormDef = this.getSystemService().getConnectorFormDefinition(systemDto); String port = getValueFromConnectorInstance(PORT, systemDto, connectorFormDef); String host = getValueFromConnectorInstance(HOST, systemDto, connectorFormDef); String user = getValueFromConnectorInstance(PRINCIPAL, systemDto, connectorFormDef); boolean ssl = Boolean.parseBoolean(getValueFromConnectorInstance(SSL, systemDto, connectorFormDef)); String password = getConfidentialValueFromConnectorInstance(CREDENTIALS, systemDto, connectorFormDef); String domainContainer = connectorType.getMetadata().get(DOMAIN_KEY); Assert.notNull(domainContainer, "Domain cannot be null!"); String newUserContainer = connectorType.getMetadata().get(NEW_USER_CONTAINER_KEY); Assert.notNull(newUserContainer, "Container for new users cannot be null!"); String searchUserContainer = connectorType.getMetadata().get(USER_SEARCH_CONTAINER_KEY); Assert.notNull(searchUserContainer, "Container for search users cannot be null!"); String deleteUserContainer = null; // Delete user container should be used only if protected mode is active. if (protectedModeSwitch) { deleteUserContainer = connectorType.getMetadata().get(DELETE_USER_CONTAINER_KEY); } String newUserContainerAD = this.findDn( MessageFormat.format("(&(distinguishedName={0})(|(objectClass=container)(objectClass=organizationalUnit)))", newUserContainer) , port, host, user, password, ssl); if (Strings.isBlank(newUserContainerAD)) { throw new ResultCodeException(AccResultCode.WIZARD_AD_CONTAINER_NOT_FOUND, ImmutableMap.of("dn", newUserContainer ) ); } String searchUserContainerAD = this.findDn( MessageFormat.format("(&(distinguishedName={0})(|(objectClass=container)(objectClass=organizationalUnit)))", searchUserContainer) , port, host, user, password, ssl); if (Strings.isBlank(searchUserContainerAD)) { throw new ResultCodeException(AccResultCode.WIZARD_AD_CONTAINER_NOT_FOUND, ImmutableMap.of("dn", searchUserContainer ) ); } if (Strings.isNotBlank(deleteUserContainer) && protectedModeSwitch) { String deleteUserContainerAD = this.findDn( MessageFormat.format("(&(distinguishedName={0})(|(objectClass=container)(objectClass=organizationalUnit)))", deleteUserContainer) , port, host, user, password, ssl); if (Strings.isBlank(deleteUserContainerAD)) { throw new ResultCodeException(AccResultCode.WIZARD_AD_CONTAINER_NOT_FOUND, ImmutableMap.of("dn", deleteUserContainer ) ); } } IdmFormDefinitionDto operationOptionsFormDefinition = getSystemService().getOperationOptionsConnectorFormDefinition(systemDto); if (operationOptionsFormDefinition != null) { // Set domain to system's operation options. operationOptionsFormDefinition = initFormAttributeDefinition(operationOptionsFormDefinition, DOMAIN_KEY, (short) 3); setValueToConnectorInstance(DOMAIN_KEY, domainContainer, systemDto, operationOptionsFormDefinition); // Set container for new users to system's operation options. operationOptionsFormDefinition = initFormAttributeDefinition(operationOptionsFormDefinition, NEW_USER_CONTAINER_KEY, (short) 4); setValueToConnectorInstance(NEW_USER_CONTAINER_KEY, newUserContainer, systemDto, operationOptionsFormDefinition); // Set container for deleted users to system's operation options. operationOptionsFormDefinition = initFormAttributeDefinition(operationOptionsFormDefinition, DELETE_USER_CONTAINER_KEY, (short) 5); setValueToConnectorInstance(DELETE_USER_CONTAINER_KEY, deleteUserContainer, systemDto, operationOptionsFormDefinition); // Set container for exists users to system's operation options. operationOptionsFormDefinition = initFormAttributeDefinition(operationOptionsFormDefinition, USER_SEARCH_CONTAINER_KEY, (short) 6); setValueToConnectorInstance(USER_SEARCH_CONTAINER_KEY, searchUserContainer, systemDto, operationOptionsFormDefinition); } String mappingSyncId = connectorType.getMetadata().get(MAPPING_SYNC_ID); String mappingId = connectorType.getMetadata().get(MAPPING_ID); if (mappingId == null && mappingSyncId == null) { // This attributes will be updated only if system doesn't have mapping. // Checking by existing mapping and not by reopen flag solves a problem with reopen wizard for to early closed wizard. For example in the certificate step. initDefaultConnectorSettings(systemDto, connectorFormDef); } // Attributes below will updated everytime (for reopen system too). // Base context for search users. // We need to searching in all containers (for new, existed and deleted users). So all three values will be use in the base context. List<Serializable> values = Lists.newArrayList(Sets.newHashSet(searchUserContainer, newUserContainer, deleteUserContainer)); this.setValueToConnectorInstance(BASE_CONTEXT_USER_KEY, values, systemDto, connectorFormDef); // Root suffixes. // First we have to find root DN (only DCs) and generate the schema for it. String root = getRoot(searchUserContainer); this.setValueToConnectorInstance(ROOT_SUFFIXES_KEY, root, systemDto, connectorFormDef); // Check system (execute a connector test) try { this.getSystemService().checkSystem(systemDto); } catch (ConnectorException ex) { throw new ResultCodeException(AccResultCode.CONNECTOR_TEST_FAILED, ImmutableMap.of("system", systemDto.getName(), "ex", ex.getLocalizedMessage()), ex); } // Generate a system schema. generateSchema(connectorType, systemDto); // Second we will set full user search / new / delete base DN and again generate the schema. this.setValueToConnectorInstance(ROOT_SUFFIXES_KEY, values, systemDto, connectorFormDef); SysSchemaObjectClassDto schemaDto = generateSchema(connectorType, systemDto); // Find sAMAccountName attribute in the schema. SysSchemaAttributeFilter schemaAttributeFilter = new SysSchemaAttributeFilter(); schemaAttributeFilter.setObjectClassId(schemaDto.getId()); schemaAttributeFilter.setSystemId(systemDto.getId()); schemaAttributeFilter.setName(SAM_ACCOUNT_NAME_ATTRIBUTE); SysSchemaAttributeDto sAMAccountNameAttribute = schemaAttributeService.find(schemaAttributeFilter, null) .stream() .findFirst() .orElse(null); if (sAMAccountNameAttribute == null) { // Attribute missing -> create it now. sAMAccountNameAttribute = createSchemaAttribute(schemaDto, SAM_ACCOUNT_NAME_ATTRIBUTE, String.class.getName(), true, true, false); } // Find __ENABLE__ attribute in the schema. schemaAttributeFilter.setName(IcAttributeInfo.ENABLE); SysSchemaAttributeDto enableAttribute = schemaAttributeService.find(schemaAttributeFilter, null) .stream() .findFirst() .orElse(null); if (enableAttribute == null) { // Attribute missing -> create it now. createSchemaAttribute(schemaDto, IcAttributeInfo.ENABLE, Boolean.class.getName(), true, true, false); } // Find __PASSWORD__ attribute in the schema. schemaAttributeFilter.setName(IcAttributeInfo.PASSWORD); SysSchemaAttributeDto passwordAttribute = schemaAttributeService.find(schemaAttributeFilter, null) .stream() .findFirst() .orElse(null); if (passwordAttribute == null) { // Attribute missing -> create it now. createSchemaAttribute(schemaDto, IcAttributeInfo.PASSWORD, GuardedString.class.getName(), false, true, false); } else { passwordAttribute.setUpdateable(true); schemaAttributeService.save(passwordAttribute); } // Find Ldap groups attribute in the schema. schemaAttributeFilter.setName(LDAP_GROUPS_ATTRIBUTE); SysSchemaAttributeDto ldapGroupsAttribute = schemaAttributeService.find(schemaAttributeFilter, null) .stream() .findFirst() .orElse(null); if (ldapGroupsAttribute == null) { // Attribute missing -> create it now. createSchemaAttribute(schemaDto, LDAP_GROUPS_ATTRIBUTE, String.class.getName(), true, true, true); } mappingId = connectorType.getMetadata().get(MAPPING_ID); if (mappingId == null) { // Create identity mapping for provisioning. SysSystemMappingDto mappingDto = new SysSystemMappingDto(); mappingDto.setObjectClass(schemaDto.getId()); mappingDto.setOperationType(SystemOperationType.PROVISIONING); mappingDto.setEntityType(SystemEntityType.IDENTITY); mappingDto.setName("AD users provisioning mapping."); mappingDto.setProtectionEnabled(protectedModeSwitch); mappingDto = systemMappingService.publish( new SystemMappingEvent( SystemMappingEvent.SystemMappingEventType.CREATE, mappingDto, ImmutableMap.of(SysSystemMappingService.ENABLE_AUTOMATIC_CREATION_OF_MAPPING, Boolean.TRUE))) .getContent(); mappingDto = systemMappingService.save(mappingDto); connectorType.getEmbedded().put(DefaultConnectorType.MAPPING_DTO_KEY, mappingDto); connectorType.getMetadata().put(DefaultConnectorType.MAPPING_ID, mappingDto.getId().toString()); } else { SysSystemMappingDto mappingDto = systemMappingService.get(UUID.fromString(mappingId)); // If protected mode switch changed, then mapping will be updated. if (mappingDto.isProtectionEnabled() != protectedModeSwitch) { mappingDto.setProtectionEnabled(protectedModeSwitch); mappingDto = systemMappingService.save(mappingDto); } connectorType.getEmbedded().put(DefaultConnectorType.MAPPING_DTO_KEY, mappingDto); } if (pairingSyncSwitch) { createPairingSync(connectorType, pairingSyncAttributeCode, schemaDto, schemaAttributeFilter, sAMAccountNameAttribute); } if (pairingSyncId != null) { // If is protected mode activated, then set strategy to LINK_PROTECTED, otherwise set DO_NOT_LINK. AbstractSysSyncConfigDto pairingSync = syncConfigService.get(UUID.fromString(pairingSyncId)); if (pairingSync instanceof SysSyncIdentityConfigDto) { SysSyncIdentityConfigDto sync = (SysSyncIdentityConfigDto) pairingSync; if (protectedModeSwitch) { sync.setInactiveOwnerBehavior(SynchronizationInactiveOwnerBehaviorType.LINK_PROTECTED); } else { sync.setInactiveOwnerBehavior(SynchronizationInactiveOwnerBehaviorType.DO_NOT_LINK); } syncConfigService.save(sync); } } } /** * Init default connector configurations. */ @SuppressWarnings({"rawtypes", "unchecked"}) protected void initDefaultConnectorSettings(SysSystemDto systemDto, IdmFormDefinitionDto connectorFormDef) { // Set the entry object classes. List values = Lists.newArrayList(ENTRY_OBJECT_CLASSES_DEFAULT_VALUES); this.setValueToConnectorInstance(ENTRY_OBJECT_CLASSES_KEY, values, systemDto, connectorFormDef); // Set the object classes to sync. values = Lists.newArrayList(ENTRY_OBJECT_CLASSES_DEFAULT_VALUES); this.setValueToConnectorInstance(OBJECT_CLASSES_TO_SYNC_KEY, values, systemDto, connectorFormDef); // Set use VLV search. this.setValueToConnectorInstance(USE_VLV_SORT_KEY, Boolean.TRUE, systemDto, connectorFormDef); // Set the VLV attribute. this.setValueToConnectorInstance(VLV_SORT_ATTRIBUTE_KEY, SAM_ACCOUNT_NAME_ATTRIBUTE, systemDto, connectorFormDef); // Set the VLV page size attribute. this.setValueToConnectorInstance(PAGE_SIZE_KEY, PAGE_SIZE_DEFAULT_VALUE, systemDto, connectorFormDef); // Default UID key. this.setValueToConnectorInstance(DEFAULT_UID_KEY, SAM_ACCOUNT_NAME_ATTRIBUTE, systemDto, connectorFormDef); } /** * Creates pairing sync mapping, schema attributes, default role and sync. */ private void createPairingSync(ConnectorTypeDto connectorType, String pairingSyncAttributeCode, SysSchemaObjectClassDto schemaDto, SysSchemaAttributeFilter schemaAttributeFilter, SysSchemaAttributeDto sAMAccountNameAttribute) { boolean protectedModeSwitch = Boolean.parseBoolean(connectorType.getMetadata().get(PROTECTED_MODE_SWITCH_KEY)); // Create identity DN EAV attribute if missing (for sync of groups). IdmFormAttributeDto attribute = getFormService().getAttribute(IdmIdentity.class, pairingSyncAttributeCode); if (attribute == null) { attribute = new IdmFormAttributeDto(pairingSyncAttributeCode, "Distinguished name (it is one-time attribute!)", PersistentType.SHORTTEXT); attribute.setDescription("This attribute is one-time and is used only for the initial pairing synchronization of accounts and groups. " + "The DN in this attribute may not be currently valid."); getFormService().saveAttribute(IdmIdentity.class, attribute); } // Create identity mapping for pairing sync. String mappingSyncId = connectorType.getMetadata().get(MAPPING_SYNC_ID); if (mappingSyncId == null) { SysSystemMappingDto mappingDto = new SysSystemMappingDto(); mappingDto.setObjectClass(schemaDto.getId()); mappingDto.setOperationType(SystemOperationType.SYNCHRONIZATION); mappingDto.setEntityType(SystemEntityType.IDENTITY); mappingDto.setName("Pairing sync mapping"); mappingDto = systemMappingService.save(mappingDto); mappingSyncId = mappingDto.getId().toString(); connectorType.getMetadata().put(MAPPING_SYNC_ID, mappingSyncId); } // Create identity mapping for pairing sync. String pairingSyncId = connectorType.getMetadata().get(PAIRING_SYNC_ID); if (pairingSyncId == null) { // Creates default role with that system. IdmRoleDto roleDto = this.createRoleSystem(connectorType); connectorType.getMetadata().put(SKIP_CREATES_ROLE_WITH_SYSTEM, Boolean.TRUE.toString()); Assert.notNull(roleDto, "Role cannot be null!"); schemaAttributeFilter.setName(IcAttributeInfo.NAME); SysSchemaAttributeDto nameSchemaAttribute = schemaAttributeService.find(schemaAttributeFilter, null) .stream() .findFirst() .orElse(null); Assert.notNull(nameSchemaAttribute, "Attribute __NAME__ cannot be null!"); // Create DN -> EAV attribute SysSystemAttributeMappingDto dnEavMappingAttribute = new SysSystemAttributeMappingDto(); dnEavMappingAttribute.setEntityAttribute(false); dnEavMappingAttribute.setExtendedAttribute(true); dnEavMappingAttribute.setIdmPropertyName(pairingSyncAttributeCode); dnEavMappingAttribute.setSchemaAttribute(nameSchemaAttribute.getId()); dnEavMappingAttribute.setUid(false); dnEavMappingAttribute.setSystemMapping(UUID.fromString(mappingSyncId)); dnEavMappingAttribute.setCached(true); dnEavMappingAttribute.setName("DN"); systemAttributeMappingService.save(dnEavMappingAttribute); // Create the correlation attribute. SysSystemAttributeMappingDto correlationAttribute = new SysSystemAttributeMappingDto(); correlationAttribute.setEntityAttribute(true); correlationAttribute.setExtendedAttribute(false); correlationAttribute.setIdmPropertyName(IdmIdentity_.username.getName()); correlationAttribute.setSchemaAttribute(sAMAccountNameAttribute.getId()); correlationAttribute.setUid(true); correlationAttribute.setSystemMapping(UUID.fromString(mappingSyncId)); correlationAttribute.setCached(true); correlationAttribute.setName(sAMAccountNameAttribute.getName()); correlationAttribute = systemAttributeMappingService.save(correlationAttribute); SysSyncIdentityConfigDto syncIdentityConfigDto = new SysSyncIdentityConfigDto(); syncIdentityConfigDto.setName(PAIRING_SYNC_NAME); syncIdentityConfigDto.setReconciliation(true); syncIdentityConfigDto.setSystemMapping(UUID.fromString(mappingSyncId)); // If is protected mode activated, then set strategy to LINK_PROTECTED, otherwise set DO_NOT_LINK. if (protectedModeSwitch) { syncIdentityConfigDto.setInactiveOwnerBehavior(SynchronizationInactiveOwnerBehaviorType.LINK_PROTECTED); } else { syncIdentityConfigDto.setInactiveOwnerBehavior(SynchronizationInactiveOwnerBehaviorType.DO_NOT_LINK); } syncIdentityConfigDto.setUnlinkedAction(SynchronizationUnlinkedActionType.LINK_AND_UPDATE_ENTITY); syncIdentityConfigDto.setMissingEntityAction(SynchronizationMissingEntityActionType.IGNORE); syncIdentityConfigDto.setMissingAccountAction(ReconciliationMissingAccountActionType.IGNORE); syncIdentityConfigDto.setLinkedAction(SynchronizationLinkedActionType.IGNORE); syncIdentityConfigDto.setDefaultRole(roleDto.getId()); syncIdentityConfigDto.setCorrelationAttribute(correlationAttribute.getId()); syncIdentityConfigDto = (SysSyncIdentityConfigDto) syncConfigService.save(syncIdentityConfigDto); syncIdentityConfigDto.setAssignDefaultRoleToAll(true); syncIdentityConfigDto.setStartAutoRoleRec(false); connectorType.getMetadata().put(PAIRING_SYNC_ID, syncIdentityConfigDto.getId().toString()); } } /** * Check attribute definition, if no exists, then will be created. */ private IdmFormDefinitionDto initFormAttributeDefinition(IdmFormDefinitionDto definitionDto, String code, Short order) { IdmFormAttributeDto attribute = definitionDto.getMappedAttributeByCode(code); if (attribute == null) { attribute = new IdmFormAttributeDto(code, code, PersistentType.SHORTTEXT); attribute.setFormDefinition(definitionDto.getId()); attribute.setSeq(order); formAttributeService.save(attribute); definitionDto = getFormService().getDefinition(definitionDto.getId()); } return definitionDto; } /** * Create schema attribute. */ private SysSchemaAttributeDto createSchemaAttribute(SysSchemaObjectClassDto schemaDto, String attributeName, String type, boolean returnByDefault, boolean updateable, boolean multivalued) { SysSchemaAttributeDto attribute; attribute = new SysSchemaAttributeDto(); attribute.setName(attributeName); attribute.setClassType(type); attribute.setObjectClass(schemaDto.getId()); attribute.setCreateable(true); attribute.setReadable(true); attribute.setMultivalued(multivalued); attribute.setReturnedByDefault(returnByDefault); attribute.setUpdateable(updateable); return schemaAttributeService.save(attribute); } /** * Generate schema. */ private SysSchemaObjectClassDto generateSchema(ConnectorTypeDto connectorType, SysSystemDto systemDto) { // Generate schema List<SysSchemaObjectClassDto> schemas = this.getSystemService().generateSchema(systemDto); SysSchemaObjectClassDto schemaAccount = schemas.stream() .filter(schema -> IcObjectClassInfo.ACCOUNT.equals(schema.getObjectClassName())).findFirst() .orElse(null); Assert.notNull(schemaAccount, "We cannot found schema for ACCOUNT!"); connectorType.getMetadata().put(SCHEMA_ID_KEY, schemaAccount.getId().toString()); return schemaAccount; } /** * Find root in container DN. -> return only DCs. */ private String getRoot(String searchUserContainer) { List<String> containers = Lists.reverse(Lists.newArrayList(searchUserContainer.split(","))); List<String> roots = Lists.newArrayList(); StringBuilder stringBuilder = new StringBuilder(); containers.forEach(container -> { if (container.trim().startsWith("DC") || container.trim().startsWith("dc")) { roots.add(container); } }); Lists.reverse(roots).forEach(root -> { stringBuilder.append(root.trim()); stringBuilder.append(','); }); String root = stringBuilder.toString(); // Remove last comma. if (Strings.isNotBlank(root) && root.contains(",")) { root = root.substring(0, root.length() - 1); } return root; } /** * Get server certificates. */ private Pair<X509Certificate, Boolean> getServerCertificate(String port, String host) { try { SSLSocket socket = null; try { socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, Integer.parseInt(port)); socket.startHandshake(); LOG.info("Certificate is already trusted for connection to the AD."); SSLSession session = socket.getSession(); Certificate[] peerCertificates = session.getPeerCertificates(); if (peerCertificates.length > 0) { return new Pair<>((X509Certificate) peerCertificates[0], Boolean.TRUE); } } catch (SSLException e) { LOG.info("Certificate is not trusted for connection to the AD."); SSLContext context = SSLContext.getInstance("TLS"); // Workaround how get server certificates from the AD server if the IdM server doesn't have trusted certificate yet. SavingTrustManager tm = new SavingTrustManager(); context.init(null, new TrustManager[]{tm}, null); SSLSocketFactory factory = context.getSocketFactory(); if (socket != null && !socket.isClosed()) { socket.close(); } socket = (SSLSocket) factory.createSocket(host, Integer.parseInt(port)); socket.setSoTimeout(10000); // Start handshake. In the case without check a trusted certificate. socket.startHandshake(); X509Certificate[] chain = tm.chain; if (chain.length > 0) { return new Pair<>(chain[0], Boolean.FALSE); } } finally { if (socket != null && !socket.isClosed()) { socket.close(); } } } catch (IOException | NoSuchAlgorithmException | KeyManagementException ex) { throw new CoreException(ex.getLocalizedMessage(), ex); } return null; } /** * Try to find authority for this certificate in AD (we want to return certificate with the biggest validity). */ private X509Certificate getCertificateFromAD(X509Certificate serverCrt, String port, String host, String user, String password) { X509Certificate resultCertificate = null; DirContext ldapContext = null; try { // Init LDAP context. Hashtable<String, String> ldapEnv = getAdEnvironment(host, "389", user, password, false); ldapContext = new InitialDirContext(ldapEnv); boolean continueSearching = true; resultCertificate = serverCrt; while (continueSearching) { X509Certificate authorityCrtOnAD = findAuthorityCrtOnAD(resultCertificate, ldapContext); if (authorityCrtOnAD != null) { // Validate certificate by found authority. try { CertificateUtils.verifyCertificate(resultCertificate, authorityCrtOnAD); } catch (CertificateException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_CONNECTOR_CRT_NOT_TRUSTED, ImmutableMap.of("serialNumber", authorityCrtOnAD.getSerialNumber().toString(16).toUpperCase() ), ex ); } } if (authorityCrtOnAD == null) { // No authority certificate was found, previous certificate is result. continueSearching = false; } else if (authorityCrtOnAD.getIssuerDN() != null && resultCertificate.getIssuerDN() != null && resultCertificate.getIssuerDN().getName().equals(authorityCrtOnAD.getIssuerDN().getName())) { // Issuer name in previous and returned authority certificate is same -> returned certificate is result. resultCertificate = authorityCrtOnAD; continueSearching = false; } else if (authorityCrtOnAD.getIssuerDN() == null || Strings.isBlank(authorityCrtOnAD.getIssuerDN().getName())) { // Found authority certificate doesn't have issuer -> it is result. resultCertificate = authorityCrtOnAD; continueSearching = false; } else { // Next round. resultCertificate = authorityCrtOnAD; } } } catch (CommunicationException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_COMMUNICATION_EXCEPTION, ImmutableMap.of("host", host ), ex ); } catch (NamingException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_OPERATION_FAILED, ImmutableMap.of("dn", serverCrt != null ? serverCrt.getSubjectDN().getName() : host) , ex ); } catch (CertificateException ex) { throw new CoreException(ex.getLocalizedMessage(), ex); } finally { if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException e) { // Only log it. LOG.error(e.getLocalizedMessage(), e); } } } return resultCertificate; } /** * Create test certificates. */ protected String createTestUser(String username, String entryDN, String port, String host, String adUser, String adPassword, boolean ssl) { DirContext ldapContext = null; try { // Init LDAP context. Hashtable<String, String> ldapEnv = getAdEnvironment(host, port, adUser, adPassword, ssl); ldapContext = new InitialDirContext(ldapEnv); // Entry's attributes. Attribute cn = new BasicAttribute("cn", username); Attribute oc = new BasicAttribute("objectClass"); oc.add("top"); oc.add("person"); oc.add("organizationalPerson"); oc.add("inetOrgPerson"); // Build the entry BasicAttributes entry = new BasicAttributes(); entry.put(cn); entry.put(oc); // Add the entry. DirContext context = ldapContext.createSubcontext(MessageFormat.format("CN={0},{1}", username, entryDN), entry); Attributes attributes = context.getAttributes(""); return (String) attributes.get("distinguishedname").get(); } catch (NameAlreadyBoundException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_CONNECTOR_DN_ALREADY_EXISTS, ImmutableMap.of("dn", MessageFormat.format("CN={0},{1}", username, entryDN)) , ex); } catch (CommunicationException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_COMMUNICATION_EXCEPTION, ImmutableMap.of("host", host ), ex ); } catch (NamingException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_OPERATION_FAILED, ImmutableMap.of("dn", MessageFormat.format("CN={0},{1}", username, entryDN)) , ex); } finally { if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException e) { // Only log it. LOG.error(e.getLocalizedMessage(), e); } } } } /** * Delete the wizard test user. */ protected void deleteTestUser(String entryDN, String port, String host, String adUser, String adPassword, boolean ssl) { DirContext ldapContext = null; try { // Init LDAP context. Hashtable<String, String> ldapEnv = getAdEnvironment(host, port, adUser, adPassword, ssl); ldapContext = new InitialDirContext(ldapEnv); // Delete the entry. ldapContext.destroySubcontext(entryDN); } catch (CommunicationException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_COMMUNICATION_EXCEPTION, ImmutableMap.of("host", host ), ex ); } catch (NamingException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_OPERATION_FAILED, ImmutableMap.of("dn", entryDN ), ex ); } finally { if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException e) { // Only log it. LOG.error(e.getLocalizedMessage(), e); } } } } /** * Assign the wizard test user to test group. */ protected void assignTestUserToGroup(String userDN, String groupDN, String port, String host, String adUser, String adPassword, boolean ssl) { DirContext ldapContext = null; try { // Init LDAP context. Hashtable<String, String> ldapEnv = getAdEnvironment(host, port, adUser, adPassword, ssl); ldapContext = new InitialDirContext(ldapEnv); ModificationItem[] roleMods = new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", userDN)) }; ldapContext.modifyAttributes(groupDN, roleMods); } catch (CommunicationException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_COMMUNICATION_EXCEPTION, ImmutableMap.of("host", host ), ex ); } catch (NamingException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_OPERATION_FAILED, ImmutableMap.of("dn", userDN ), ex ); } finally { if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException e) { // Only log it. LOG.error(e.getLocalizedMessage(), e); } } } } /** * Find given DN. If not exists, then return null. */ protected String findDn(String filter, String port, String host, String adUser, String adPassword, boolean ssl) { DirContext ldapContext = null; try { // Init LDAP context. Hashtable<String, String> ldapEnv = getAdEnvironment(host, port, adUser, adPassword, ssl); ldapContext = new InitialDirContext(ldapEnv); // Get the configuration naming context. Attributes ldapContextAttributes = ldapContext.getAttributes(""); String defaultNamingContext = ldapContextAttributes.get("defaultNamingContext").get().toString(); LOG.info("AD default naming context: {}.", defaultNamingContext); // Create the search controls SearchControls searchControls = new SearchControls(); //Specify the search scope searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for objects using the filter NamingEnumeration<SearchResult> result = ldapContext.search(defaultNamingContext, filter, searchControls); if (result.hasMoreElements()) { return MessageFormat.format("{0},{1}", result.next().getName(), defaultNamingContext); } } catch (CommunicationException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_COMMUNICATION_EXCEPTION, ImmutableMap.of("host", host ), ex ); } catch (NamingException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_OPERATION_FAILED, ImmutableMap.of("dn", filter), ex ); } finally { if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException e) { // Only log it. LOG.error(e.getLocalizedMessage(), e); } } } return null; } /** * Find dnsHostName (domain) on the AD. */ protected String findDnsHostName(String port, String host, String adUser, String adPassword, boolean ssl) { DirContext ldapContext = null; try { // Init LDAP context. Hashtable<String, String> ldapEnv = getAdEnvironment(host, port, adUser, adPassword, ssl); ldapContext = new InitialDirContext(ldapEnv); // Get the configuration naming context. Attributes ldapContextAttributes = ldapContext.getAttributes(""); return ldapContextAttributes.get("dnsHostName").get().toString(); } catch (CommunicationException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_COMMUNICATION_EXCEPTION, ImmutableMap.of("host", host ), ex ); } catch (NamingException ex) { throw new ResultCodeException(AccResultCode.WIZARD_AD_OPERATION_FAILED, ImmutableMap.of("dn", "dnsHostName"), ex ); } finally { if (ldapContext != null) { try { ldapContext.close(); } catch (NamingException e) { // Only log it. LOG.error(e.getLocalizedMessage(), e); } } } } /** * Compile LDAP environment properties. */ private Hashtable<String, String> getAdEnvironment(String host, String port, String user, String password, boolean ssl) { Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11); ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // Use ldaps for SSL if (ssl) { ldapEnv.put(Context.PROVIDER_URL, MessageFormat.format("ldaps://{0}:{1}", host, port)); } else { ldapEnv.put(Context.PROVIDER_URL, MessageFormat.format("ldap://{0}:{1}", host, port)); } ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); ldapEnv.put(Context.SECURITY_PRINCIPAL, user); ldapEnv.put(Context.SECURITY_CREDENTIALS, password); return ldapEnv; } /** * Find authority for given certificate on AD. */ private X509Certificate findAuthorityCrtOnAD(X509Certificate certificate, DirContext ldapContext) throws NamingException, CertificateException { LOG.info("Cert Subject DN: {}.", certificate.getSubjectDN().getName()); LOG.info("Cert Issuer DN: {}.", certificate.getIssuerDN().getName()); String issuer = certificate.getIssuerDN().getName(); if (Strings.isNotBlank(issuer)) { // Issuer exist, we will try to get certificate of the authority from AD server. // Get the configuration naming context. Attributes ldapContextAttributes = ldapContext.getAttributes(""); String configurationNamingContext = ldapContextAttributes.get("configurationNamingContext").get().toString(); LOG.info("AD Configuration naming context: {}.", configurationNamingContext); // Create the search controls SearchControls searchControls = new SearchControls(); //Specify the attributes to return String[] returnedAttributes = {"cACertificate"}; searchControls.setReturningAttributes(returnedAttributes); //Specify the search scope searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for objects using the filter NamingEnumeration<SearchResult> result = ldapContext.search(configurationNamingContext, MessageFormat.format("(&(cACertificateDN={0})(objectClass=pKIEnrollmentService))", issuer), searchControls); //Loop through the search results while (result.hasMoreElements()) { SearchResult sr = result.next(); Attributes attrs = sr.getAttributes(); Attribute caAttribute = attrs.get(returnedAttributes[0]); if (caAttribute != null) { Object value = caAttribute.get(); if (value instanceof byte[]) { byte[] bytes = (byte[]) value; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); return CertificateUtils.getCertificate509(byteArrayInputStream); } } } } return null; } /** * Workaround how get server certificates from the AD server if the IdM server doesn't have trusted certificate yet. */ private static class SavingTrustManager implements X509TrustManager { private X509Certificate[] chain; public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { this.chain = chain; } } /** * Create entity state for wizard test user */ private IdmEntityStateDto createEntityStateWithTestUser(SysSystemDto systemDto, String createdUserDN) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("entityId", systemDto.getId()); // Mark state with created user DN. parameters.put(TEST_CREATED_USER_DN_KEY, createdUserDN); DefaultResultModel resultModel = new DefaultResultModel(AccResultCode.WIZARD_AD_CREATED_TEST_USER_DN, parameters); IdmEntityStateDto entityStateDto = new IdmEntityStateDto(); entityStateDto.setResult( new OperationResultDto .Builder(OperationState.CREATED) .setModel(resultModel) .build()); return entityStateManager.saveState(systemDto, entityStateDto); } /** * Convert Date to the zoned date time in string. */ private String getZonedDateTime(Date date) { String zonedDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toString(); return zonedDateTime.split("\\[")[0]; } /** * Folder with trusted certificates. */ private String getTrustedCaFolder() { return Paths.get(attachmentManager.getStoragePath(), "trustedCA").toString(); } /** * Generate file name for given certificate. */ private String getCaFileName(X509Certificate crt) { String subjectDn = SpinalCase.format(crt.getSubjectDN().getName()); if (subjectDn.length() > 20) { subjectDn = subjectDn.substring(0, 19); } return MessageFormat.format("{0}_{1}.pem", subjectDn, crt.getSerialNumber().toString(16).toUpperCase()); } @Override public int getOrder() { return 200; } }
package com.hubspot.singularity.scheduler; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.mesos.Protos.FrameworkID; import org.apache.mesos.Protos.Offer; import org.apache.mesos.Protos.OfferID; import org.apache.mesos.Protos.Resource; import org.apache.mesos.Protos.SlaveID; import org.apache.mesos.Protos.TaskID; import org.apache.mesos.Protos.TaskInfo; import org.apache.mesos.Protos.TaskState; import org.apache.mesos.Protos.TaskStatus; import org.apache.mesos.Protos.Value.Scalar; import org.apache.mesos.Protos.Value.Type; import org.apache.mesos.SchedulerDriver; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.name.Named; import com.hubspot.baragon.models.BaragonRequestState; import com.hubspot.mesos.MesosUtils; import com.hubspot.singularity.DeployState; import com.hubspot.singularity.LoadBalancerRequestType; import com.hubspot.singularity.LoadBalancerRequestType.LoadBalancerRequestId; import com.hubspot.singularity.RequestState; import com.hubspot.singularity.SingularityCuratorTestBase; import com.hubspot.singularity.SingularityDeploy; import com.hubspot.singularity.SingularityDeployBuilder; import com.hubspot.singularity.SingularityDeployMarker; import com.hubspot.singularity.SingularityDeployResult; import com.hubspot.singularity.SingularityLoadBalancerUpdate; import com.hubspot.singularity.SingularityLoadBalancerUpdate.LoadBalancerMethod; import com.hubspot.singularity.SingularityMainModule; import com.hubspot.singularity.SingularityPendingDeploy; import com.hubspot.singularity.SingularityPendingRequest; import com.hubspot.singularity.SingularityPendingRequest.PendingType; import com.hubspot.singularity.SingularityPendingTask; import com.hubspot.singularity.SingularityPendingTaskId; import com.hubspot.singularity.SingularityRequest; import com.hubspot.singularity.SingularityRequestBuilder; import com.hubspot.singularity.SingularityRequestDeployState; import com.hubspot.singularity.SingularityRequestHistory.RequestHistoryType; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.SingularityTaskStatusHolder; import com.hubspot.singularity.SlavePlacement; import com.hubspot.singularity.api.SingularityDeployRequest; import com.hubspot.singularity.api.SingularityPauseRequest; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.RequestManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.mesos.SchedulerDriverSupplier; import com.hubspot.singularity.mesos.SingularityMesosScheduler; import com.hubspot.singularity.resources.DeployResource; import com.hubspot.singularity.resources.RequestResource; import com.hubspot.singularity.scheduler.SingularityTaskReconciliation.ReconciliationState; import com.ning.http.client.AsyncHttpClient; public class SingularitySchedulerTest extends SingularityCuratorTestBase { @Inject private Provider<SingularitySchedulerStateCache> stateCacheProvider; @Inject private SingularityMesosScheduler sms; @Inject private RequestManager requestManager; @Inject private DeployManager deployManager; @Inject private TaskManager taskManager; @Inject private SchedulerDriverSupplier driverSupplier; private SchedulerDriver driver; @Inject private SingularityScheduler scheduler; @Inject private SingularityDeployChecker deployChecker; @Inject private RequestResource requestResource; @Inject private DeployResource deployResource; @Inject private SingularityCleaner cleaner; @Inject private SingularityConfiguration configuration; @Inject private SingularityCooldownChecker cooldownChecker; @Inject private AsyncHttpClient httpClient; @Inject private TestingLoadBalancerClient testingLbClient; @Inject private SingularityTaskReconciliation taskReconciliation; @Inject @Named(SingularityMainModule.SERVER_ID_PROPERTY) private String serverId; @After public void teardown() throws Exception { if (httpClient != null) { httpClient.close(); } } @Before public final void setupDriver() throws Exception { driver = driverSupplier.get().get(); } private Offer createOffer(double cpus, double memory) { return createOffer(cpus, memory, "slave1", "host1"); } private Offer createOffer(double cpus, double memory, String slave, String host) { SlaveID slaveId = SlaveID.newBuilder().setValue(slave).build(); FrameworkID frameworkId = FrameworkID.newBuilder().setValue("framework1").build(); Random r = new Random(); return Offer.newBuilder() .setId(OfferID.newBuilder().setValue("offer" + r.nextInt(1000)).build()) .setFrameworkId(frameworkId) .setSlaveId(slaveId) .setHostname(host) .addResources(Resource.newBuilder().setType(Type.SCALAR).setName(MesosUtils.CPUS).setScalar(Scalar.newBuilder().setValue(cpus))) .addResources(Resource.newBuilder().setType(Type.SCALAR).setName(MesosUtils.MEMORY).setScalar(Scalar.newBuilder().setValue(memory))) .build(); } public SingularityTask launchTask(SingularityRequest request, SingularityDeploy deploy, TaskState initialTaskState) { SingularityTaskId taskId = new SingularityTaskId(request.getId(), deploy.getId(), System.currentTimeMillis(), 1, "host", "rack"); SingularityPendingTaskId pendingTaskId = new SingularityPendingTaskId(request.getId(), deploy.getId(), System.currentTimeMillis(), 1, PendingType.IMMEDIATE); SingularityPendingTask pendingTask = new SingularityPendingTask(pendingTaskId, Optional.<String> absent()); SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask); TaskID taskIdProto = TaskID.newBuilder().setValue(taskId.toString()).build(); Offer offer = createOffer(125, 1024); TaskInfo taskInfo = TaskInfo.newBuilder() .setSlaveId(offer.getSlaveId()) .setTaskId(taskIdProto) .setName("name") .build(); SingularityTask task = new SingularityTask(taskRequest, taskId, offer, taskInfo); taskManager.createPendingTasks(Arrays.asList(pendingTask)); taskManager.createTaskAndDeletePendingTask(task); statusUpdate(task, initialTaskState); return task; } public void statusUpdate(SingularityTask task, TaskState state, Optional<Long> timestamp) { TaskStatus.Builder bldr = TaskStatus.newBuilder() .setTaskId(task.getMesosTask().getTaskId()) .setState(state); if (timestamp.isPresent()) { bldr.setTimestamp(timestamp.get() / 1000); } sms.statusUpdate(driver, bldr.build()); } public void statusUpdate(SingularityTask task, TaskState state) { statusUpdate(task, state, Optional.<Long> absent()); } private String requestId; private SingularityRequest request; private String schedule = "*/1 * * * * ?"; public void initLoadBalancedRequest() { privateInitRequest(true, false); } public void initScheduledRequest() { privateInitRequest(false, true); } private void privateInitRequest(boolean isLoadBalanced, boolean isScheduled) { requestId = "test-request"; SingularityRequestBuilder bldr = new SingularityRequestBuilder(requestId) .setLoadBalanced(Optional.of(isLoadBalanced)); if (isScheduled) { bldr.setQuartzSchedule(Optional.of(schedule)); } request = bldr.build(); requestManager.activate(request, RequestHistoryType.CREATED, Optional.<String> absent()); } public void initRequest() { privateInitRequest(false, false); } private String firstDeployId; private SingularityDeployMarker firstDeployMarker; private SingularityDeploy firstDeploy; public void initFirstDeploy() { firstDeployId = "firstDeployId"; firstDeployMarker = new SingularityDeployMarker(requestId, firstDeployId, System.currentTimeMillis(), Optional.<String> absent()); firstDeploy = new SingularityDeployBuilder(requestId, firstDeployId).setCommand(Optional.of("sleep 100")).build(); deployManager.saveDeploy(request, firstDeployMarker, firstDeploy); finishDeploy(firstDeployMarker, firstDeploy); } private String secondDeployId; private SingularityDeployMarker secondDeployMarker; private SingularityDeploy secondDeploy; public void initSecondDeploy() { secondDeployId = "secondDeployId"; secondDeployMarker = new SingularityDeployMarker(requestId, secondDeployId, System.currentTimeMillis(), Optional.<String> absent()); secondDeploy = new SingularityDeployBuilder(requestId, secondDeployId).setCommand(Optional.of("sleep 100")).build(); deployManager.saveDeploy(request, secondDeployMarker, secondDeploy); startDeploy(secondDeployMarker); } public void startDeploy(SingularityDeployMarker deployMarker) { deployManager.savePendingDeploy(new SingularityPendingDeploy(deployMarker, Optional.<SingularityLoadBalancerUpdate> absent(), DeployState.WAITING)); } public void finishDeploy(SingularityDeployMarker marker, SingularityDeploy deploy) { deployManager.saveDeployResult(marker, Optional.of(deploy), new SingularityDeployResult(DeployState.SUCCEEDED)); deployManager.saveNewRequestDeployState(new SingularityRequestDeployState(requestId, Optional.of(marker), Optional.<SingularityDeployMarker> absent())); } public SingularityTask startTask(SingularityDeploy deploy) { return launchTask(request, deploy, TaskState.TASK_RUNNING); } @Test public void testSchedulerIsolatesPendingTasksBasedOnDeploy() { initRequest(); initFirstDeploy(); initSecondDeploy(); SingularityPendingTask p1 = new SingularityPendingTask(new SingularityPendingTaskId(requestId, firstDeployId, System.currentTimeMillis(), 1, PendingType.ONEOFF), Optional.<String> absent()); SingularityPendingTask p2 = new SingularityPendingTask(new SingularityPendingTaskId(requestId, firstDeployId, System.currentTimeMillis(), 1, PendingType.TASK_DONE), Optional.<String> absent()); SingularityPendingTask p3 = new SingularityPendingTask(new SingularityPendingTaskId(requestId, secondDeployId, System.currentTimeMillis(), 1, PendingType.TASK_DONE), Optional.<String> absent()); List<SingularityPendingTask> pendingTasks = Arrays.asList(p1, p2, p3); taskManager.createPendingTasks(pendingTasks); requestManager.addToPendingQueue(new SingularityPendingRequest(requestId, secondDeployId, PendingType.NEW_DEPLOY)); scheduler.drainPendingQueue(stateCacheProvider.get()); // we expect there to be 3 pending tasks : List<SingularityPendingTask> returnedScheduledTasks = taskManager.getPendingTasks(); Assert.assertEquals(3, returnedScheduledTasks.size()); Assert.assertTrue(returnedScheduledTasks.contains(p1)); Assert.assertTrue(returnedScheduledTasks.contains(p2)); Assert.assertTrue(!returnedScheduledTasks.contains(p3)); boolean found = false; for (SingularityPendingTask pendingTask : returnedScheduledTasks) { if (pendingTask.getPendingTaskId().getDeployId().equals(secondDeployId)) { found = true; Assert.assertEquals(PendingType.NEW_DEPLOY, pendingTask.getPendingTaskId().getPendingType()); } } Assert.assertTrue(found); } @Test public void testDeployManagerHandlesFailedLBTask() { initLoadBalancedRequest(); initFirstDeploy(); SingularityTask firstTask = startTask(firstDeploy); initSecondDeploy(); SingularityTask secondTask = startTask(secondDeploy); // this should cause an LB call to happen: deployChecker.checkDeploys(); Assert.assertTrue(taskManager.getLoadBalancerState(secondTask.getTaskId(), LoadBalancerRequestType.ADD).isPresent()); Assert.assertTrue(!taskManager.getLoadBalancerState(secondTask.getTaskId(), LoadBalancerRequestType.DEPLOY).isPresent()); Assert.assertTrue(!taskManager.getLoadBalancerState(secondTask.getTaskId(), LoadBalancerRequestType.REMOVE).isPresent()); statusUpdate(secondTask, TaskState.TASK_FAILED); statusUpdate(firstTask, TaskState.TASK_FAILED); deployChecker.checkDeploys(); Assert.assertTrue(deployManager.getDeployResult(requestId, secondDeployId).get().getDeployState() == DeployState.FAILED); List<SingularityPendingTask> pendingTasks = taskManager.getPendingTasks(); Assert.assertTrue(pendingTasks.size() == 1); Assert.assertTrue(pendingTasks.get(0).getPendingTaskId().getDeployId().equals(firstDeployId)); } @Test public void testDeployClearsObsoleteScheduledTasks() { initRequest(); initFirstDeploy(); initSecondDeploy(); SingularityPendingTaskId taskIdOne = new SingularityPendingTaskId(requestId, firstDeployId, System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3), 1, PendingType.IMMEDIATE); SingularityPendingTask taskOne = new SingularityPendingTask(taskIdOne, Optional.<String> absent()); SingularityPendingTaskId taskIdTwo = new SingularityPendingTaskId(requestId, firstDeployId, System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1), 2, PendingType.IMMEDIATE); SingularityPendingTask taskTwo = new SingularityPendingTask(taskIdTwo, Optional.<String> absent()); SingularityPendingTaskId taskIdThree = new SingularityPendingTaskId(requestId, secondDeployId, System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3), 1, PendingType.IMMEDIATE); SingularityPendingTask taskThree = new SingularityPendingTask(taskIdThree, Optional.<String> absent()); SingularityPendingTaskId taskIdFour = new SingularityPendingTaskId(requestId + "hi", firstDeployId, System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3), 5, PendingType.IMMEDIATE); SingularityPendingTask taskFour = new SingularityPendingTask(taskIdFour, Optional.<String> absent()); taskManager.createPendingTasks(Arrays.asList(taskOne, taskTwo, taskThree, taskFour)); launchTask(request, secondDeploy, TaskState.TASK_RUNNING); deployChecker.checkDeploys(); List<SingularityPendingTaskId> pendingTaskIds = taskManager.getPendingTaskIds(); Assert.assertTrue(!pendingTaskIds.contains(taskIdOne)); Assert.assertTrue(!pendingTaskIds.contains(taskIdTwo)); Assert.assertTrue(pendingTaskIds.contains(taskIdThree)); Assert.assertTrue(pendingTaskIds.contains(taskIdFour)); } @Test public void testAfterDeployWaitsForScheduledTaskToFinish() { initScheduledRequest(); initFirstDeploy(); SingularityTask firstTask = launchTask(request, firstDeploy, TaskState.TASK_RUNNING); Assert.assertTrue(taskManager.getPendingTasks().isEmpty()); Assert.assertTrue(taskManager.getActiveTaskIds().contains(firstTask.getTaskId())); Assert.assertEquals(1, taskManager.getActiveTaskIds().size()); Assert.assertTrue(taskManager.getCleanupTaskIds().isEmpty()); deploy("nextDeployId"); deployChecker.checkDeploys(); scheduler.drainPendingQueue(stateCacheProvider.get()); // no second task should be scheduled Assert.assertTrue(taskManager.getPendingTasks().isEmpty()); Assert.assertTrue(taskManager.getActiveTaskIds().contains(firstTask.getTaskId())); Assert.assertEquals(1, taskManager.getActiveTaskIds().size()); Assert.assertTrue(!taskManager.getCleanupTaskIds().isEmpty()); statusUpdate(firstTask, TaskState.TASK_FINISHED); scheduler.drainPendingQueue(stateCacheProvider.get()); cleaner.drainCleanupQueue(); Assert.assertTrue(!taskManager.getPendingTasks().isEmpty()); Assert.assertTrue(taskManager.getActiveTaskIds().isEmpty()); Assert.assertTrue(taskManager.getCleanupTaskIds().isEmpty()); SingularityPendingTaskId pendingTaskId = taskManager.getPendingTaskIds().get(0); Assert.assertEquals("nextDeployId", pendingTaskId.getDeployId()); Assert.assertEquals(requestId, pendingTaskId.getRequestId()); } private SingularityPendingTask createAndSchedulePendingTask(String deployId) { Random random = new Random(); SingularityPendingTaskId pendingTaskId = new SingularityPendingTaskId(requestId, deployId, System.currentTimeMillis() + TimeUnit.DAYS.toMillis(random.nextInt(3)), random.nextInt(10), PendingType.IMMEDIATE); SingularityPendingTask pendingTask = new SingularityPendingTask(pendingTaskId, Optional.<String> absent()); taskManager.createPendingTasks(Arrays.asList(pendingTask)); return pendingTask; } @Test public void testCleanerLeavesPausedRequestTasksByDemand() { initScheduledRequest(); initFirstDeploy(); SingularityTask firstTask = launchTask(request, firstDeploy, TaskState.TASK_RUNNING); createAndSchedulePendingTask(firstDeployId); requestResource.pause(requestId, Optional.<String> absent(), Optional.of(new SingularityPauseRequest(Optional.of("testuser"), Optional.of(false)))); cleaner.drainCleanupQueue(); Assert.assertTrue(taskManager.getKilledTaskIdRecords().isEmpty()); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); Assert.assertTrue(requestManager.getCleanupRequests().isEmpty()); statusUpdate(firstTask, TaskState.TASK_FINISHED); // make sure something new isn't scheduled! Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); } @Test public void testKilledTaskIdRecords() { initScheduledRequest(); initFirstDeploy(); SingularityTask firstTask = launchTask(request, firstDeploy, TaskState.TASK_RUNNING); requestResource.deleteRequest(requestId, Optional.<String> absent()); Assert.assertTrue(requestManager.getCleanupRequests().size() == 1); cleaner.drainCleanupQueue(); Assert.assertTrue(requestManager.getCleanupRequests().isEmpty()); Assert.assertTrue(!taskManager.getKilledTaskIdRecords().isEmpty()); cleaner.drainCleanupQueue(); Assert.assertTrue(!taskManager.getKilledTaskIdRecords().isEmpty()); statusUpdate(firstTask, TaskState.TASK_KILLED); Assert.assertTrue(taskManager.getKilledTaskIdRecords().isEmpty()); } @Test public void testLongRunningTaskKills() { initScheduledRequest(); initFirstDeploy(); launchTask(request, firstDeploy, TaskState.TASK_RUNNING); initSecondDeploy(); deployChecker.checkDeploys(); Assert.assertTrue(taskManager.getKilledTaskIdRecords().isEmpty()); Assert.assertTrue(!taskManager.getCleanupTasks().isEmpty()); cleaner.drainCleanupQueue(); Assert.assertTrue(taskManager.getKilledTaskIdRecords().isEmpty()); Assert.assertTrue(!taskManager.getCleanupTasks().isEmpty()); requestManager.activate(request.toBuilder().setKillOldNonLongRunningTasksAfterMillis(Optional.<Long> of(0L)).build(), RequestHistoryType.CREATED, Optional.<String> absent()); cleaner.drainCleanupQueue(); Assert.assertTrue(!taskManager.getKilledTaskIdRecords().isEmpty()); Assert.assertTrue(taskManager.getCleanupTasks().isEmpty()); } @Test public void testSchedulerCanBatchOnOffers() { initRequest(); initFirstDeploy(); requestResource.submit(request.toBuilder().setInstances(Optional.of(3)).build(), Optional.<String> absent()); scheduler.drainPendingQueue(stateCacheProvider.get()); List<Offer> oneOffer = Arrays.asList(createOffer(12, 1024)); sms.resourceOffers(driver, oneOffer); Assert.assertTrue(taskManager.getActiveTasks().size() == 3); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); Assert.assertTrue(requestManager.getPendingRequests().isEmpty()); } @Test public void testSchedulerExhaustsOffers() { initRequest(); initFirstDeploy(); requestResource.submit(request.toBuilder().setInstances(Optional.of(10)).build(), Optional.<String> absent()); scheduler.drainPendingQueue(stateCacheProvider.get()); sms.resourceOffers(driver, Arrays.asList(createOffer(2, 1024), createOffer(1, 1024))); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 3); Assert.assertTrue(taskManager.getPendingTaskIds().size() == 7); } @Test public void testSchedulerRandomizesOffers() { initRequest(); initFirstDeploy(); requestResource.submit(request.toBuilder().setInstances(Optional.of(15)).build(), Optional.<String> absent()); scheduler.drainPendingQueue(stateCacheProvider.get()); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 1024), createOffer(20, 1024))); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 15); Set<String> offerIds = Sets.newHashSet(); for (SingularityTask activeTask : taskManager.getActiveTasks()) { offerIds.add(activeTask.getOffer().getId().getValue()); } Assert.assertTrue(offerIds.size() == 2); } @Test public void testSchedulerHandlesFinishedTasks() { initScheduledRequest(); initFirstDeploy(); schedule = "*/1 * * * * ? 1995"; // cause it to be pending requestResource.submit(request.toBuilder().setQuartzSchedule(Optional.of(schedule)).build(), Optional.<String> absent()); scheduler.drainPendingQueue(stateCacheProvider.get()); Assert.assertTrue(requestResource.getActiveRequests().isEmpty()); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.FINISHED); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); schedule = "*/1 * * * * ?"; requestResource.submit(request.toBuilder().setQuartzSchedule(Optional.of(schedule)).build(), Optional.<String> absent()); scheduler.drainPendingQueue(stateCacheProvider.get()); Assert.assertTrue(!requestResource.getActiveRequests().isEmpty()); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.ACTIVE); Assert.assertTrue(!taskManager.getPendingTaskIds().isEmpty()); } private void deploy(String deployId) { deploy(deployId, Optional.<Boolean> absent()); } private void deploy(String deployId, Optional<Boolean> unpauseOnDeploy) { deployResource.deploy(new SingularityDeployRequest(new SingularityDeployBuilder(requestId, deployId).setCommand(Optional.of("sleep 1")).build(), Optional.<String> absent(), unpauseOnDeploy)); } @Test public void testScheduledJobLivesThroughDeploy() { initScheduledRequest(); initFirstDeploy(); createAndSchedulePendingTask(firstDeployId); Assert.assertTrue(!taskManager.getPendingTaskIds().isEmpty()); deploy("d2"); scheduler.drainPendingQueue(stateCacheProvider.get()); deployChecker.checkDeploys(); scheduler.drainPendingQueue(stateCacheProvider.get()); Assert.assertTrue(!taskManager.getPendingTaskIds().isEmpty()); } @Test public void testOneOffsDontRunByThemselves() { requestId = "oneoffRequest"; SingularityRequestBuilder bldr = new SingularityRequestBuilder(requestId); bldr.setDaemon(Optional.of(Boolean.FALSE)); requestResource.submit(bldr.build(), Optional.<String> absent()); Assert.assertTrue(requestManager.getPendingRequests().isEmpty()); deploy("d2"); Assert.assertTrue(requestManager.getPendingRequests().isEmpty()); deployChecker.checkDeploys(); Assert.assertTrue(requestManager.getPendingRequests().isEmpty()); } @Test public void testCooldownAfterSequentialFailures() { initRequest(); initFirstDeploy(); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.ACTIVE); configuration.setCooldownAfterFailures(2); configuration.setCooldownExpiresAfterMinutes(30); SingularityTask firstTask = startTask(firstDeploy); SingularityTask secondTask = startTask(firstDeploy); statusUpdate(firstTask, TaskState.TASK_FAILED); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.ACTIVE); statusUpdate(secondTask, TaskState.TASK_FAILED); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.SYSTEM_COOLDOWN); cooldownChecker.checkCooldowns(); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.SYSTEM_COOLDOWN); SingularityTask thirdTask = startTask(firstDeploy); statusUpdate(thirdTask, TaskState.TASK_FINISHED); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.ACTIVE); } @Test public void testCooldownOnlyWhenTasksRapidlyFail() { initRequest(); initFirstDeploy(); configuration.setCooldownAfterFailures(1); configuration.setCooldownExpiresAfterMinutes(1); SingularityTask firstTask = startTask(firstDeploy); statusUpdate(firstTask, TaskState.TASK_FAILED, Optional.of(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(5))); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.ACTIVE); SingularityTask secondTask = startTask(firstDeploy); statusUpdate(secondTask, TaskState.TASK_FAILED); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.SYSTEM_COOLDOWN); } @Test public void testSlavePlacementSeparate() { initRequest(); initFirstDeploy(); saveAndSchedule(request.toBuilder().setInstances(Optional.of(2)).setSlavePlacement(Optional.of(SlavePlacement.SEPARATE))); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"), createOffer(20, 20000, "slave1", "host1"))); Assert.assertTrue(taskManager.getPendingTaskIds().size() == 1); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 1); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"))); Assert.assertTrue(taskManager.getPendingTaskIds().size() == 1); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 1); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave2", "host2"))); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 2); } @Test public void testSlavePlacementOptimistic() { initRequest(); initFirstDeploy(); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"), createOffer(20, 20000, "slave2", "host2"))); saveAndSchedule(request.toBuilder().setInstances(Optional.of(3)).setSlavePlacement(Optional.of(SlavePlacement.OPTIMISTIC))); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"))); Assert.assertTrue(taskManager.getActiveTaskIds().size() < 3); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"))); Assert.assertTrue(taskManager.getActiveTaskIds().size() < 3); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave2", "host2"))); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 3); } @Test public void testSlavePlacementOptimisticSingleOffer() { initRequest(); initFirstDeploy(); saveAndSchedule(request.toBuilder().setInstances(Optional.of(3)).setSlavePlacement(Optional.of(SlavePlacement.OPTIMISTIC))); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"), createOffer(20, 20000, "slave2", "host2"))); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 3); } @Test public void testSlavePlacementGreedy() { initRequest(); initFirstDeploy(); saveAndSchedule(request.toBuilder().setInstances(Optional.of(3)).setSlavePlacement(Optional.of(SlavePlacement.GREEDY))); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"))); Assert.assertTrue(taskManager.getActiveTaskIds().size() == 3); } private void saveAndSchedule(SingularityRequestBuilder bldr) { requestManager.activate(bldr.build(), RequestHistoryType.UPDATED, Optional.<String> absent()); requestManager.addToPendingQueue(new SingularityPendingRequest(bldr.getId(), firstDeployId, PendingType.UPDATED_REQUEST)); scheduler.drainPendingQueue(stateCacheProvider.get()); } private void saveLoadBalancerState(BaragonRequestState brs, SingularityTaskId taskId, LoadBalancerRequestType lbrt) { final LoadBalancerRequestId lbri = new LoadBalancerRequestId(taskId.getId(), lbrt, Optional.<Integer> absent()); SingularityLoadBalancerUpdate update = new SingularityLoadBalancerUpdate(brs, lbri, Optional.<String> absent(), System.currentTimeMillis(), LoadBalancerMethod.CHECK_STATE, null); taskManager.saveLoadBalancerState(taskId, lbrt, update); } @Test public void testLBCleanup() { initLoadBalancedRequest(); initFirstDeploy(); SingularityTask task = launchTask(request, firstDeploy, TaskState.TASK_RUNNING); saveLoadBalancerState(BaragonRequestState.SUCCESS, task.getTaskId(), LoadBalancerRequestType.ADD); statusUpdate(task, TaskState.TASK_FAILED); Assert.assertTrue(!taskManager.getLBCleanupTasks().isEmpty()); testingLbClient.setNextBaragonRequestState(BaragonRequestState.WAITING); cleaner.drainCleanupQueue(); Assert.assertTrue(!taskManager.getLBCleanupTasks().isEmpty()); Optional<SingularityLoadBalancerUpdate> lbUpdate = taskManager.getLoadBalancerState(task.getTaskId(), LoadBalancerRequestType.REMOVE); Assert.assertTrue(lbUpdate.isPresent()); Assert.assertTrue(lbUpdate.get().getLoadBalancerState() == BaragonRequestState.WAITING); testingLbClient.setNextBaragonRequestState(BaragonRequestState.FAILED); cleaner.drainCleanupQueue(); Assert.assertTrue(!taskManager.getLBCleanupTasks().isEmpty()); lbUpdate = taskManager.getLoadBalancerState(task.getTaskId(), LoadBalancerRequestType.REMOVE); Assert.assertTrue(lbUpdate.isPresent()); Assert.assertTrue(lbUpdate.get().getLoadBalancerState() == BaragonRequestState.FAILED); testingLbClient.setNextBaragonRequestState(BaragonRequestState.SUCCESS); cleaner.drainCleanupQueue(); Assert.assertTrue(taskManager.getLBCleanupTasks().isEmpty()); lbUpdate = taskManager.getLoadBalancerState(task.getTaskId(), LoadBalancerRequestType.REMOVE); Assert.assertTrue(lbUpdate.isPresent()); Assert.assertTrue(lbUpdate.get().getLoadBalancerState() == BaragonRequestState.SUCCESS); Assert.assertTrue(lbUpdate.get().getLoadBalancerRequestId().getAttemptNumber() == 2); } @Test public void testUnpauseoOnDeploy() { initRequest(); initFirstDeploy(); requestManager.pause(request, Optional.<String> absent()); boolean exception = false; try { deploy("d2"); } catch (Exception e) { exception = true; } Assert.assertTrue(exception); deploy("d3", Optional.of(true)); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.DEPLOYING_TO_UNPAUSE); scheduler.drainPendingQueue(stateCacheProvider.get()); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"))); statusUpdate(taskManager.getActiveTasks().get(0), TaskState.TASK_FAILED); deployChecker.checkDeploys(); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.PAUSED); Assert.assertTrue(taskManager.getActiveTaskIds().isEmpty()); Assert.assertTrue(taskManager.getPendingTaskIds().isEmpty()); Assert.assertTrue(requestManager.getPendingRequests().isEmpty()); deploy("d4", Optional.of(true)); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.DEPLOYING_TO_UNPAUSE); scheduler.drainPendingQueue(stateCacheProvider.get()); sms.resourceOffers(driver, Arrays.asList(createOffer(20, 20000, "slave1", "host1"))); statusUpdate(taskManager.getActiveTasks().get(0), TaskState.TASK_RUNNING); deployChecker.checkDeploys(); Assert.assertTrue(requestManager.getRequest(requestId).get().getState() == RequestState.ACTIVE); } private void sleep(long millis) { try { Thread.sleep(millis); } catch (Exception e) { throw Throwables.propagate(e); } } private void saveLastActiveTaskStatus(SingularityTask task, Optional<TaskStatus> taskStatus, long millisAdjustment) { taskManager.saveLastActiveTaskStatus(new SingularityTaskStatusHolder(task.getTaskId(), taskStatus, System.currentTimeMillis() + millisAdjustment, serverId, Optional.of("slaveId"))); } private TaskStatus buildTaskStatus(SingularityTask task) { return TaskStatus.newBuilder().setTaskId(TaskID.newBuilder().setValue(task.getTaskId().getId())).setState(TaskState.TASK_RUNNING).build(); } @Test public void testReconciliation() { Assert.assertTrue(!taskReconciliation.isReconciliationRunning()); configuration.setCheckReconcileWhenRunningEveryMillis(1); initRequest(); initFirstDeploy(); Assert.assertTrue(taskReconciliation.startReconciliation() == ReconciliationState.STARTED); sleep(50); Assert.assertTrue(!taskReconciliation.isReconciliationRunning()); SingularityTask taskOne = launchTask(request, firstDeploy, TaskState.TASK_STARTING); SingularityTask taskTwo = launchTask(request, firstDeploy, TaskState.TASK_RUNNING); saveLastActiveTaskStatus(taskOne, Optional.<TaskStatus> absent(), -1000); Assert.assertTrue(taskReconciliation.startReconciliation() == ReconciliationState.STARTED); Assert.assertTrue(taskReconciliation.startReconciliation() == ReconciliationState.ALREADY_RUNNING); sleep(50); Assert.assertTrue(taskReconciliation.isReconciliationRunning()); saveLastActiveTaskStatus(taskOne, Optional.of(buildTaskStatus(taskOne)), +1000); sleep(50); Assert.assertTrue(taskReconciliation.isReconciliationRunning()); saveLastActiveTaskStatus(taskTwo, Optional.of(buildTaskStatus(taskTwo)), +1000); sleep(50); Assert.assertTrue(!taskReconciliation.isReconciliationRunning()); } }
package net.sf.taverna.t2.workbench.ui.servicepanel; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import javax.swing.tree.DefaultMutableTreeNode; import net.sf.taverna.t2.servicedescriptions.ServiceDescription; import net.sf.taverna.t2.workbench.ui.servicepanel.tree.Filter; public class ServiceFilter implements Filter { private String filterString; private boolean superseded; private String[] filterLowerCaseSplit; private final Object rootToIgnore; public ServiceFilter(String filterString, Object rootToIgnore) { this.filterString = filterString; this.rootToIgnore = rootToIgnore; this.filterLowerCaseSplit = filterString.toLowerCase().split(" "); this.superseded = false; } @SuppressWarnings("unchecked") private boolean basicFilter(DefaultMutableTreeNode node) { if (node == rootToIgnore) { return false; } if (filterString.equals("")) { return true; } if (node.getUserObject() instanceof ServiceDescription) { ServiceDescription serviceDescription = (ServiceDescription) node .getUserObject(); search: for (String searchTerm : filterLowerCaseSplit) { if (superseded) { return false; } String[] typeSplit = searchTerm.split(":", 2); String type; String keyword; if (typeSplit.length == 2) { type = typeSplit[0]; keyword = typeSplit[1]; } else { type = null; keyword = searchTerm; } try { BeanInfo beanInfo = Introspector .getBeanInfo(serviceDescription.getClass()); for (PropertyDescriptor property : beanInfo .getPropertyDescriptors()) { if (superseded) { return false; } if (type == null && !property.isHidden() && !property.isExpert() || property.getName().equalsIgnoreCase(type)) { Object readProperty = property.getReadMethod() .invoke(serviceDescription, new Object[0]); if (readProperty == null) { continue; } if (readProperty.toString().toLowerCase().contains( keyword)) { //System.out.println("Found " + keyword + " in " + property.getName() + ": " + readProperty); // Found it, try next word continue search; } else { // Dig deeper? } } } return false; } catch (IntrospectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } return true; } for (String searchString : filterLowerCaseSplit) { if (!node.getUserObject().toString().toLowerCase().contains( searchString)) { return false; } } return true; } public boolean pass(DefaultMutableTreeNode node) { return basicFilter(node); } public String filterRepresentation(String original) { return original; } /** * @return the superseded */ public boolean isSuperseded() { return superseded; } /** * @param superseded * the superseded to set */ public void setSuperseded(boolean superseded) { this.superseded = superseded; } }
package com.smartdevicelink.managers.file; import android.content.Context; import android.net.Uri; import com.smartdevicelink.AndroidTestCase2; import com.smartdevicelink.managers.BaseSubManager; import com.smartdevicelink.managers.CompletionListener; import com.smartdevicelink.managers.file.filetypes.SdlArtwork; import com.smartdevicelink.managers.file.filetypes.SdlFile; import com.smartdevicelink.proxy.RPCMessage; import com.smartdevicelink.proxy.RPCRequest; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.rpc.DeleteFile; import com.smartdevicelink.proxy.rpc.DeleteFileResponse; import com.smartdevicelink.proxy.rpc.ListFiles; import com.smartdevicelink.proxy.rpc.ListFilesResponse; import com.smartdevicelink.proxy.rpc.PutFile; import com.smartdevicelink.proxy.rpc.PutFileResponse; import com.smartdevicelink.proxy.rpc.enums.FileType; import com.smartdevicelink.proxy.rpc.enums.Result; import com.smartdevicelink.proxy.rpc.enums.StaticIconName; import com.smartdevicelink.proxy.rpc.listeners.OnMultipleRequestListener; import com.smartdevicelink.test.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * This is a unit test class for the SmartDeviceLink library manager class : * {@link FileManager} */ public class FileManagerTests extends AndroidTestCase2 { public static final String TAG = "FileManagerTests"; private Context mTestContext; private SdlFile validFile; // SETUP / HELPERS @Override public void setUp() throws Exception{ super.setUp(); mTestContext = this.getContext(); validFile = new SdlFile(); validFile.setName(Test.GENERAL_STRING); validFile.setFileData(Test.GENERAL_BYTE_ARRAY); validFile.setPersistent(false); } @Override public void tearDown() throws Exception { super.tearDown(); } private Answer<Void> onPutFileFailureOnError = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); RPCRequest message = (RPCRequest) args[0]; if (message instanceof PutFile) { int correlationId = message.getCorrelationID(); Result resultCode = Result.REJECTED; PutFileResponse putFileResponse = new PutFileResponse(); putFileResponse.setSuccess(false); message.getOnRPCResponseListener().onError(correlationId, resultCode, "Binary data empty"); } return null; } }; private Answer<Void> onSendRequestsFailOnError = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); List<RPCRequest> rpcs = (List<RPCRequest>) args[0]; OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1]; if (rpcs.get(0) instanceof PutFile) { Result resultCode = Result.REJECTED; for (RPCRequest message : rpcs) { int correlationId = message.getCorrelationID(); listener.addCorrelationId(correlationId); PutFileResponse putFileResponse = new PutFileResponse(); putFileResponse.setSuccess(true); listener.onError(correlationId, resultCode, "Binary data empty"); } listener.onFinished(); } return null; } }; private Answer<Void> onListFileUploadSuccess = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); List<RPCRequest> rpcs = (List<RPCRequest>) args[0]; OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1]; if (rpcs.get(0) instanceof PutFile) { for (RPCRequest message : rpcs) { int correlationId = message.getCorrelationID(); listener.addCorrelationId(correlationId); PutFileResponse putFileResponse = new PutFileResponse(); putFileResponse.setSuccess(true); listener.onResponse(correlationId, putFileResponse); } listener.onFinished(); } return null; } }; private Answer<Void> onListFilesSuccess = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); RPCRequest message = (RPCRequest) args[0]; if(message instanceof ListFiles){ int correlationId = message.getCorrelationID(); ListFilesResponse listFilesResponse = new ListFilesResponse(); listFilesResponse.setFilenames(Test.GENERAL_STRING_LIST); listFilesResponse.setSpaceAvailable(Test.GENERAL_INT); listFilesResponse.setSuccess(true); message.getOnRPCResponseListener().onResponse(correlationId, listFilesResponse); } return null; } }; private Answer<Void> onListFilesFailure = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); RPCRequest message = (RPCRequest) args[0]; if(message instanceof ListFiles){ int correlationId = message.getCorrelationID(); ListFilesResponse listFilesResponse = new ListFilesResponse(); listFilesResponse.setSuccess(false); message.getOnRPCResponseListener().onResponse(correlationId, listFilesResponse); } return null; } }; private Answer<Void> onPutFileSuccess = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); RPCRequest message = (RPCRequest) args[0]; if(message instanceof PutFile){ int correlationId = message.getCorrelationID(); PutFileResponse putFileResponse = new PutFileResponse(); putFileResponse.setSuccess(true); putFileResponse.setSpaceAvailable(Test.GENERAL_INT); message.getOnRPCResponseListener().onResponse(correlationId, putFileResponse); } return null; } }; private Answer<Void> onPutFileFailure = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); RPCRequest message = (RPCRequest) args[0]; if(message instanceof PutFile){ int correlationId = message.getCorrelationID(); PutFileResponse putFileResponse = new PutFileResponse(); putFileResponse.setSuccess(false); message.getOnRPCResponseListener().onResponse(correlationId, putFileResponse); } return null; } }; private Answer<Void> onSendRequestsSuccess = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); List<RPCRequest> rpcs = (List<RPCRequest>) args[0]; OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1]; if(rpcs.get(0) instanceof PutFile){ for(RPCRequest message : rpcs){ int correlationId = message.getCorrelationID(); listener.addCorrelationId(correlationId); PutFileResponse putFileResponse = new PutFileResponse(); putFileResponse.setSuccess(true); listener.onResponse(correlationId, putFileResponse); } } return null; } }; private Answer<Void> onListDeleteRequestSuccess = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); List<RPCRequest> rpcs = (List<RPCRequest>) args[0]; OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1]; if (rpcs.get(0) instanceof DeleteFile) { for (RPCRequest message : rpcs) { int correlationId = message.getCorrelationID(); listener.addCorrelationId(correlationId); DeleteFileResponse deleteFileResponse = new DeleteFileResponse(); deleteFileResponse.setSuccess(true); listener.onResponse(correlationId, deleteFileResponse); } listener.onFinished(); } return null; } }; private Answer<Void> onListDeleteRequestFail = new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); List<RPCRequest> rpcs = (List<RPCRequest>) args[0]; OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1]; if (rpcs.get(0) instanceof DeleteFile) { Result resultCode = Result.REJECTED; for (RPCRequest message : rpcs) { int correlationId = message.getCorrelationID(); listener.addCorrelationId(correlationId); DeleteFileResponse deleteFileResponse = new DeleteFileResponse(); deleteFileResponse.setSuccess(true); listener.onError(correlationId, resultCode, "Binary data empty"); } listener.onFinished(); } return null; } }; // TESTS /** * Test deleting list of files, success */ public void testDeleteRemoteFilesWithNamesSuccess(){ final ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onListDeleteRequestSuccess).when(internalInterface).sendRequests(any(List.class), any(OnMultipleRequestListener.class)); final List<String> fileNames = new ArrayList<>(); fileNames.add("Julian"); fileNames.add("Jake"); FileManagerConfig fileManagerConfig = new FileManagerConfig(); fileManagerConfig.setFileRetryCount(2); final FileManager fileManager = new FileManager(internalInterface,mTestContext,fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); fileManager.deleteRemoteFilesWithNames(fileNames, new MultipleFileCompletionListener() { @Override public void onComplete(Map<String, String> errors) { assertTrue(errors == null); } }); } }); } /** * Test deleting list of files, fail */ public void testDeleteRemoteFilesWithNamesFail(){ final ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onListDeleteRequestFail).when(internalInterface).sendRequests(any(List.class), any(OnMultipleRequestListener.class)); final List<String> fileNames = new ArrayList<>(); fileNames.add("Julian"); fileNames.add("Jake"); FileManagerConfig fileManagerConfig = new FileManagerConfig(); fileManagerConfig.setFileRetryCount(2); final FileManager fileManager = new FileManager(internalInterface,mTestContext,fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); fileManager.deleteRemoteFilesWithNames(fileNames, new MultipleFileCompletionListener() { @Override public void onComplete(Map<String, String> errors) { assertTrue(errors.size() == 2); } }); } }); } /** * Test reUploading failed file */ public void testFileUploadRetry(){ final ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onPutFileFailureOnError).when(internalInterface).sendRPC(any(PutFile.class)); FileManagerConfig fileManagerConfig = new FileManagerConfig(); fileManagerConfig.setFileRetryCount(2); validFile.setType(FileType.AUDIO_MP3); final FileManager fileManager = new FileManager(internalInterface, mTestContext,fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); fileManager.uploadFile(validFile, new CompletionListener() { @Override public void onComplete(boolean success) { assertFalse(success); } }); } }); verify(internalInterface, times(4)).sendRPC(any(RPCMessage.class)); } /** * Test reUploading failed Artwork */ public void testArtworkUploadRetry(){ final ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onPutFileFailureOnError).when(internalInterface).sendRPC(any(PutFile.class)); final SdlFile validFile2 = new SdlFile(); validFile2.setName(Test.GENERAL_STRING + "2"); validFile2.setFileData(Test.GENERAL_BYTE_ARRAY); validFile2.setPersistent(false); validFile2.setType(FileType.GRAPHIC_PNG); final SdlFile validFile3 = new SdlFile(); validFile3.setName(Test.GENERAL_STRING + "3"); validFile3.setFileData(Test.GENERAL_BYTE_ARRAY); validFile3.setPersistent(false); validFile3.setType(FileType.GRAPHIC_BMP); validFile.setType(FileType.GRAPHIC_JPEG); FileManagerConfig fileManagerConfig = new FileManagerConfig(); fileManagerConfig.setArtworkRetryCount(2); final FileManager fileManager = new FileManager(internalInterface, mTestContext,fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); fileManager.uploadFile(validFile, new CompletionListener() { @Override public void onComplete(boolean success) { assertFalse(success); verify(internalInterface, times(4)).sendRPC(any(RPCMessage.class)); } }); fileManager.uploadFile(validFile2, new CompletionListener() { @Override public void onComplete(boolean success) { assertFalse(success); verify(internalInterface, times(7)).sendRPC(any(RPCMessage.class)); } }); fileManager.uploadFile(validFile3, new CompletionListener() { @Override public void onComplete(boolean success) { assertFalse(success); } }); } }); verify(internalInterface, times(10)).sendRPC(any(RPCMessage.class)); } /** * Test retry uploading failed list of files */ public void testListFilesUploadRetry(){ final ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onSendRequestsFailOnError).when(internalInterface).sendRequests(any(List.class), any(OnMultipleRequestListener.class)); SdlFile validFile2 = new SdlFile(); validFile2.setName(Test.GENERAL_STRING + "2"); validFile2.setFileData(Test.GENERAL_BYTE_ARRAY); validFile2.setPersistent(false); validFile2.setType(FileType.GRAPHIC_JPEG); validFile.setType(FileType.AUDIO_WAVE); final List<SdlFile> list = new ArrayList<>(); list.add(validFile); list.add(validFile2); FileManagerConfig fileManagerConfig = new FileManagerConfig(); fileManagerConfig.setArtworkRetryCount(2); fileManagerConfig.setFileRetryCount(4); final FileManager fileManager = new FileManager(internalInterface, mTestContext,fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { fileManager.uploadFiles(list, new MultipleFileCompletionListener() { @Override public void onComplete(Map<String, String> errors) { assertTrue(errors.size() == 2); // We need to make sure it kept track of both Files } }); } }); verify(internalInterface, times(5)).sendRequests(any(List.class),any(OnMultipleRequestListener.class)); } public void testInitializationSuccess(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); assertEquals(fileManager.getState(), BaseSubManager.READY); assertEquals(fileManager.getRemoteFileNames(), Test.GENERAL_STRING_LIST); assertEquals(Test.GENERAL_INT, fileManager.getBytesAvailable()); } }); } public void testInitializationFailure(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesFailure).when(internalInterface).sendRPCRequest(any(ListFiles.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertFalse(success); assertEquals(fileManager.getState(), BaseSubManager.ERROR); assertEquals(BaseFileManager.SPACE_AVAILABLE_MAX_VALUE, fileManager.getBytesAvailable()); } }); } /** * Test file upload, success */ public void testFileUploadSuccess() { ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onPutFileSuccess).when(internalInterface).sendRPC(any(PutFile.class)); FileManagerConfig fileManagerConfig = new FileManagerConfig(); final FileManager fileManager = new FileManager(internalInterface, mTestContext, fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); fileManager.uploadFile(validFile, new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); } }); } }); assertTrue(fileManager.getRemoteFileNames().contains(validFile.getName())); assertTrue(fileManager.hasUploadedFile(validFile)); assertEquals(Test.GENERAL_INT, fileManager.getBytesAvailable()); } public void testFileUploadFailure(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); doAnswer(onPutFileFailure).when(internalInterface).sendRPCRequest(any(PutFile.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); fileManager.uploadFile(validFile, new CompletionListener() { @Override public void onComplete(boolean success) { assertFalse(success); assertFalse(fileManager.getRemoteFileNames().contains(validFile.getName())); assertFalse(fileManager.hasUploadedFile(validFile)); } }); } }); } public void testFileUploadForStaticIcon(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); SdlArtwork artwork = new SdlArtwork(StaticIconName.ALBUM); fileManager.uploadFile(artwork, new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); } }); } }); } public void testInvalidSdlFileInput(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); SdlFile sdlFile = new SdlFile(); // Don't set name sdlFile.setFileData(Test.GENERAL_BYTE_ARRAY); checkForUploadFailure(fileManager, sdlFile); sdlFile = new SdlFile(); sdlFile.setName(Test.GENERAL_STRING); // Don't set data checkForUploadFailure(fileManager, sdlFile); sdlFile = new SdlFile(); sdlFile.setName(Test.GENERAL_STRING); // Give an invalid resource ID sdlFile.setResourceId(Test.GENERAL_INT); checkForUploadFailure(fileManager, sdlFile); sdlFile = new SdlFile(); sdlFile.setName(Test.GENERAL_STRING); // Set invalid Uri Uri testUri = Uri.parse("http: sdlFile.setUri(testUri); checkForUploadFailure(fileManager, sdlFile); } }); } private void checkForUploadFailure(FileManager fileManager, SdlFile sdlFile){ boolean error = false; try { fileManager.uploadFile(sdlFile, new CompletionListener() { @Override public void onComplete(boolean success) {} }); }catch (IllegalArgumentException e){ error = true; } assertTrue(error); } public void testInvalidSdlArtworkInput(){ SdlArtwork sdlArtwork = new SdlArtwork(); // Set invalid type for(FileType fileType : FileType.values()){ boolean shouldError = true, didError = false; if(fileType.equals(FileType.GRAPHIC_BMP) || fileType.equals(FileType.GRAPHIC_PNG) || fileType.equals(FileType.GRAPHIC_JPEG)){ shouldError = false; } try{ sdlArtwork.setType(fileType); }catch(IllegalArgumentException e){ didError = true; } assertEquals(shouldError, didError); } } /** * Test Multiple File Uploads, success */ public void testMultipleFileUpload() { ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPC(any(ListFiles.class)); doAnswer(onListFileUploadSuccess).when(internalInterface).sendRequests(any(List.class), any(OnMultipleRequestListener.class)); FileManagerConfig fileManagerConfig = new FileManagerConfig(); final FileManager fileManager = new FileManager(internalInterface, mTestContext, fileManagerConfig); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); final List<SdlFile> filesToUpload = new ArrayList<>(); filesToUpload.add(validFile); SdlFile validFile2 = new SdlFile(); validFile2.setName(Test.GENERAL_STRING + "2"); validFile2.setFileData(Test.GENERAL_BYTE_ARRAY); validFile2.setPersistent(false); validFile2.setType(FileType.GRAPHIC_JPEG); filesToUpload.add(validFile2); fileManager.uploadFiles(filesToUpload, new MultipleFileCompletionListener() { @Override public void onComplete(Map<String, String> errors) { assertNull(errors); } }); } }); } public void testMultipleFileUploadPartialFailure(){ final String failureReason = "No space available"; ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); Answer<Void> onSendRequestsFailure = new Answer<Void>() { private int responseNum = 0; @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); List<RPCRequest> rpcs = (List<RPCRequest>) args[0]; OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1]; if(rpcs.get(0) instanceof PutFile){ for(RPCRequest message : rpcs){ int correlationId = message.getCorrelationID(); listener.addCorrelationId(correlationId); PutFileResponse putFileResponse = new PutFileResponse(); if(responseNum++ % 2 == 0){ listener.onError(correlationId, Result.OUT_OF_MEMORY, failureReason); }else{ putFileResponse.setSuccess(true); listener.onResponse(correlationId, putFileResponse); } } } return null; } }; doAnswer(onSendRequestsFailure).when(internalInterface).sendRequests(any(List.class), any(OnMultipleRequestListener.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); final String baseFileName = "file"; int fileNum = 0; final List<SdlFile> filesToUpload = new ArrayList<>(); SdlFile sdlFile = new SdlFile(); sdlFile.setName(baseFileName + fileNum++); Uri uri = Uri.parse("android.resource://" + mTestContext.getPackageName() + "/drawable/ic_sdl"); sdlFile.setUri(uri); filesToUpload.add(sdlFile); sdlFile = new SdlFile(); sdlFile.setName(baseFileName + fileNum++); sdlFile.setResourceId(com.smartdevicelink.test.R.drawable.ic_sdl); filesToUpload.add(sdlFile); sdlFile = new SdlFile(); sdlFile.setName(baseFileName + fileNum++); sdlFile.setFileData(Test.GENERAL_BYTE_ARRAY); sdlFile.setPersistent(true); sdlFile.setType(FileType.BINARY); filesToUpload.add(sdlFile); fileManager.uploadFiles(filesToUpload, new MultipleFileCompletionListener() { @Override public void onComplete(Map<String, String> errors) { assertNotNull(errors); for(int i = 0; i < filesToUpload.size(); i++){ if(i % 2 == 0){ assertTrue(errors.containsKey(filesToUpload.get(i).getName())); assertEquals(FileManager.buildErrorString(Result.OUT_OF_MEMORY, failureReason), errors.get(filesToUpload.get(i).getName())); }else{ assertFalse(errors.containsKey(filesToUpload.get(i).getName())); } } List <String> uploadedFileNames = fileManager.getRemoteFileNames(); for(int i = 0; i < filesToUpload.size(); i++){ if(i % 2 == 0){ assertFalse(uploadedFileNames.contains(filesToUpload.get(i).getName())); }else{ assertTrue(uploadedFileNames.contains(filesToUpload.get(i).getName())); } } } }); } }); } public void testMultipleArtworkUploadSuccess(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); doAnswer(onSendRequestsSuccess).when(internalInterface).sendRequests(any(List.class), any(OnMultipleRequestListener.class)); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(success); int fileNum = 1; final List<SdlArtwork> artworkToUpload = new ArrayList<>(); SdlArtwork sdlArtwork = new SdlArtwork(); sdlArtwork.setName("art" + fileNum++); Uri uri = Uri.parse("android.resource://" + mTestContext.getPackageName() + "/drawable/ic_sdl"); sdlArtwork.setUri(uri); sdlArtwork.setType(FileType.GRAPHIC_PNG); artworkToUpload.add(sdlArtwork); sdlArtwork = new SdlArtwork(); sdlArtwork.setName("art" + fileNum++); uri = Uri.parse("android.resource://" + mTestContext.getPackageName() + "/drawable/sdl_tray_icon"); sdlArtwork.setUri(uri); sdlArtwork.setType(FileType.GRAPHIC_PNG); artworkToUpload.add(sdlArtwork); fileManager.uploadFiles(artworkToUpload, new MultipleFileCompletionListener() { @Override public void onComplete(Map<String, String> errors) { assertNull(errors); List < String > uploadedFileNames = fileManager.getRemoteFileNames(); for(SdlArtwork artwork : artworkToUpload){ assertTrue(uploadedFileNames.contains(artwork.getName())); } } }); } }); } public void testPersistentFileUploaded(){ ISdl internalInterface = mock(ISdl.class); doAnswer(onListFilesSuccess).when(internalInterface).sendRPCRequest(any(ListFiles.class)); final SdlFile file = new SdlFile(); file.setName(Test.GENERAL_STRING_LIST.get(0)); file.setPersistent(true); final FileManager fileManager = new FileManager(internalInterface, mTestContext); fileManager.start(new CompletionListener() { @Override public void onComplete(boolean success) { assertTrue(fileManager.hasUploadedFile(file)); } }); } /** * Test FileManagerConfig */ public void testFileManagerConfig() { FileManagerConfig fileManagerConfig = new FileManagerConfig(); fileManagerConfig.setFileRetryCount(2); fileManagerConfig.setArtworkRetryCount(2); assertEquals(fileManagerConfig.getArtworkRetryCount(), 2); assertEquals(fileManagerConfig.getFileRetryCount(), 2); } }
package uk.ac.ebi.quickgo.annotation.download.header; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.StringJoiner; import org.springframework.http.MediaType; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; public class TsvHeaderCreator implements HeaderCreator{ private static final String OUTPUT_DELIMITER = "\t"; static final String GENE_PRODUCT_ID = "GENE PRODUCT ID"; static final String SYMBOL = "SYMBOL"; static final String QUALIFIER = "QUALIFIER"; static final String GO_TERM = "GO TERM"; static final String GO_NAME = "GO NAME"; static final String SLIMMED_FROM = "SLIMMED FROM"; static final String ECO_ID = "ECO_ID"; static final String GO_EVIDENCE_CODE = "GO EVIDENCE CODE"; static final String REFERENCE = "REFERENCE"; static final String WITH_FROM = "WITH/FROM"; static final String TAXON_ID = "TAXON ID"; static final String ASSIGNED_BY = "ASSIGNED BY"; static final String ANNOTATION_EXTENSION = "ANNOTATION EXTENSION"; static final String DATE = "DATE"; static final String TAXON_NAME = "TAXON NAME"; public static final String GENE_PRODUCT_ID_FIELD_NAME = "geneProductId"; public static final String SYMBOL_FIELD_NAME = "symbol"; public static final String QUALIFIER_FIELD_NAME = "qualifier"; public static final String GO_TERM_FIELD_NAME = "goId"; public static final String GO_NAME_FIELD_NAME = "goName"; public static final String ECO_ID_FIELD_NAME = "evidenceCode"; public static final String GO_EVIDENCE_CODE_FIELD_NAME = "goEvidence"; public static final String REFERENCE_FIELD_NAME = "reference"; public static final String WITH_FROM_FIELD_NAME = "withFrom"; public static final String TAXON_ID_FIELD_NAME = "taxonId"; public static final String ASSIGNED_BY_FIELD_NAME = "assignedBy"; public static final String ANNOTATION_EXTENSION_FIELD_NAME = "extensions"; public static final String DATE_FIELD_NAME = "date"; public static final String TAXON_NAME_FIELD_NAME = "taxonName"; /** * Write the contents of the header to the ResponseBodyEmitter instance. * @param emitter streams the header content to the client * @param content holds values used to control or populate the header output.; */ @Override public void write(ResponseBodyEmitter emitter, HeaderContent content) { Preconditions.checkArgument(Objects.nonNull(emitter), "The GTypeHeaderCreator emitter must not be null"); Preconditions.checkArgument(Objects.nonNull(content), "The GTypeHeaderCreator content instance must not be " + "null"); try { emitter.send(colHeadings(content) + "\n", MediaType.TEXT_PLAIN); } catch (IOException e) { throw new RuntimeException("Failed to send TSV download header", e); } } private String colHeadings(HeaderContent headerContent) { StringJoiner tsvJoiner = new StringJoiner(OUTPUT_DELIMITER); //todo missing the following fields that come from other services yet to be plugged in //todo name, synonym, type from the gene product service List<String> selectedFields = headerContent.selectedFields(); if (selectedFields.isEmpty() || selectedFields.contains(GENE_PRODUCT_ID_FIELD_NAME)) { tsvJoiner.add(GENE_PRODUCT_ID); } if (selectedFields.isEmpty() || selectedFields.contains(SYMBOL_FIELD_NAME)) { tsvJoiner.add(SYMBOL); } if (selectedFields.isEmpty() || selectedFields.contains(QUALIFIER_FIELD_NAME)) { tsvJoiner.add(QUALIFIER); } if (selectedFields.isEmpty() || selectedFields.contains(GO_TERM_FIELD_NAME)) { tsvJoiner.add(GO_TERM); } if (headerContent.isSlimmed()) { tsvJoiner.add(SLIMMED_FROM); } if (selectedFields.isEmpty() || selectedFields.contains(GO_NAME_FIELD_NAME)) { tsvJoiner.add(GO_NAME); } if (selectedFields.isEmpty() || selectedFields.contains(ECO_ID_FIELD_NAME)) { tsvJoiner.add(ECO_ID); } if (selectedFields.isEmpty() || selectedFields.contains(GO_EVIDENCE_CODE_FIELD_NAME)) { tsvJoiner.add(GO_EVIDENCE_CODE); } if (selectedFields.isEmpty() || selectedFields.contains(REFERENCE_FIELD_NAME)) { tsvJoiner.add(REFERENCE); } if (selectedFields.isEmpty() || selectedFields.contains(WITH_FROM_FIELD_NAME)) { tsvJoiner.add(WITH_FROM); } if (selectedFields.isEmpty() || selectedFields.contains(TAXON_ID_FIELD_NAME)) { tsvJoiner.add(TAXON_ID); } if (selectedFields.isEmpty() || selectedFields.contains(ASSIGNED_BY_FIELD_NAME)) { tsvJoiner.add(ASSIGNED_BY); } if (selectedFields.isEmpty() || selectedFields.contains(ANNOTATION_EXTENSION_FIELD_NAME)) { tsvJoiner.add(ANNOTATION_EXTENSION); } if (selectedFields.isEmpty() || selectedFields.contains(DATE_FIELD_NAME)) { tsvJoiner.add(DATE); } if (selectedFields.isEmpty() || selectedFields.contains(TAXON_NAME_FIELD_NAME)) { tsvJoiner.add(TAXON_NAME); } return tsvJoiner.toString(); } }
package de.test.antennapod.service.playback; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.annotation.UiThreadTest; import android.support.test.filters.LargeTest; import org.awaitility.Awaitility; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import de.danoeh.antennapod.core.event.FeedItemEvent; import de.danoeh.antennapod.core.event.QueueEvent; import de.danoeh.antennapod.core.feed.EventDistributor; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.service.playback.PlaybackServiceTaskManager; import de.danoeh.antennapod.core.storage.DBReader; import de.danoeh.antennapod.core.storage.DBWriter; import de.danoeh.antennapod.core.storage.PodDBAdapter; import de.danoeh.antennapod.core.util.playback.Playable; import io.reactivex.functions.Consumer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test class for PlaybackServiceTaskManager */ @LargeTest public class PlaybackServiceTaskManagerTest { @After public void tearDown() { PodDBAdapter.deleteDatabase(); } @Before public void setUp() { // create new database Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); PodDBAdapter.init(context); PodDBAdapter.deleteDatabase(); PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.close(); } @Test public void testInit() { Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(context, defaultPSTM); pstm.shutdown(); } private List<FeedItem> writeTestQueue(String pref) { final int NUM_ITEMS = 10; Feed f = new Feed(0, null, "title", "link", "d", null, null, null, null, "id", null, "null", "url", false); f.setItems(new ArrayList<>()); for (int i = 0; i < NUM_ITEMS; i++) { f.getItems().add(new FeedItem(0, pref + i, pref + i, "link", new Date(), FeedItem.PLAYED, f)); } PodDBAdapter adapter = PodDBAdapter.getInstance(); adapter.open(); adapter.setCompleteFeed(f); adapter.setQueue(f.getItems()); adapter.close(); for (FeedItem item : f.getItems()) { assertTrue(item.getId() != 0); } return f.getItems(); } @Test public void testGetQueueWriteBeforeCreation() throws InterruptedException { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); List<FeedItem> queue = writeTestQueue("a"); assertNotNull(queue); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); List<FeedItem> testQueue = pstm.getQueue(); assertNotNull(testQueue); assertTrue(queue.size() == testQueue.size()); for (int i = 0; i < queue.size(); i++) { assertTrue(queue.get(i).getId() == testQueue.get(i).getId()); } pstm.shutdown(); } @Test public void testGetQueueWriteAfterCreation() throws InterruptedException { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); List<FeedItem> testQueue = pstm.getQueue(); assertNotNull(testQueue); assertTrue(testQueue.isEmpty()); final CountDownLatch countDownLatch = new CountDownLatch(1); EventDistributor.EventListener queueListener = new EventDistributor.EventListener() { @Override public void update(EventDistributor eventDistributor, Integer arg) { countDownLatch.countDown(); } }; EventDistributor.getInstance().register(queueListener); List<FeedItem> queue = writeTestQueue("a"); EventBus.getDefault().post(QueueEvent.setQueue(queue)); countDownLatch.await(5000, TimeUnit.MILLISECONDS); assertNotNull(queue); testQueue = pstm.getQueue(); assertNotNull(testQueue); assertTrue(queue.size() == testQueue.size()); for (int i = 0; i < queue.size(); i++) { assertTrue(queue.get(i).getId() == testQueue.get(i).getId()); } pstm.shutdown(); } @Test public void testQueueUpdatedUponDownloadComplete() throws Exception { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); { // Setup test data List<FeedItem> queue = writeTestQueue("a"); FeedItem item = DBReader.getFeedItem(queue.get(0).getId()); FeedMedia media = new FeedMedia(item, "http://example.com/episode.mp3", 12345, "audio/mp3"); item.setMedia(media); DBWriter.setFeedMedia(media).get(); DBWriter.setFeedItem(item).get(); } PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); final FeedItem testItem = pstm.getQueue().get(0); assertFalse("The item should not yet be downloaded", testItem.getMedia().isDownloaded()); withFeedItemEventListener( feedItemEventListener -> { // simulate download complete (in DownloadService.MediaHandlerThread) FeedItem item = DBReader.getFeedItem(testItem.getId()); item.getMedia().setDownloaded(true); item.getMedia().setFile_url("file://123"); item.setAutoDownload(false); DBWriter.setFeedMedia(item.getMedia()).get(); DBWriter.setFeedItem(item).get(); Awaitility.await() .atMost(1000, TimeUnit.MILLISECONDS) .until(() -> feedItemEventListener.getEvents().size() > 0); final FeedItem itemUpdated = pstm.getQueue().get(0); assertTrue("media.isDownloaded() should be true - The queue in PlaybackService should be updated after download is completed", itemUpdated.getMedia().isDownloaded()); }); pstm.shutdown(); } /** * Provides an listener subscribing to {@link FeedItemEvent} that the callers can use * * Note: it uses RxJava's version of {@link Consumer} because it allows exceptions to be thrown. */ private static void withFeedItemEventListener(Consumer<FeedItemEventListener> consumer) throws Exception { FeedItemEventListener feedItemEventListener = new FeedItemEventListener(); try { EventBus.getDefault().register(feedItemEventListener); consumer.accept(feedItemEventListener); } finally { EventBus.getDefault().unregister(feedItemEventListener); } } private static class FeedItemEventListener { private final List<FeedItemEvent> events = new ArrayList<>(); @Subscribe public void onEvent(FeedItemEvent event) { events.add(event); } List<? extends FeedItemEvent> getEvents() { return events; } } @Test public void testStartPositionSaver() throws InterruptedException { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); final int NUM_COUNTDOWNS = 2; final int TIMEOUT = 3 * PlaybackServiceTaskManager.POSITION_SAVER_WAITING_INTERVAL; final CountDownLatch countDownLatch = new CountDownLatch(NUM_COUNTDOWNS); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { countDownLatch.countDown(); } @Override public void onSleepTimerAlmostExpired() { } @Override public void onSleepTimerExpired() { } @Override public void onSleepTimerReset() { } @Override public void onWidgetUpdaterTick() { } @Override public void onChapterLoaded(Playable media) { } }); pstm.startPositionSaver(); countDownLatch.await(TIMEOUT, TimeUnit.MILLISECONDS); pstm.shutdown(); } @Test public void testIsPositionSaverActive() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.startPositionSaver(); assertTrue(pstm.isPositionSaverActive()); pstm.shutdown(); } @Test public void testCancelPositionSaver() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.startPositionSaver(); pstm.cancelPositionSaver(); assertFalse(pstm.isPositionSaverActive()); pstm.shutdown(); } @Test public void testStartWidgetUpdater() throws InterruptedException { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); final int NUM_COUNTDOWNS = 2; final int TIMEOUT = 3 * PlaybackServiceTaskManager.WIDGET_UPDATER_NOTIFICATION_INTERVAL; final CountDownLatch countDownLatch = new CountDownLatch(NUM_COUNTDOWNS); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { } @Override public void onSleepTimerAlmostExpired() { } @Override public void onSleepTimerExpired() { } @Override public void onSleepTimerReset() { } @Override public void onWidgetUpdaterTick() { countDownLatch.countDown(); } @Override public void onChapterLoaded(Playable media) { } }); pstm.startWidgetUpdater(); countDownLatch.await(TIMEOUT, TimeUnit.MILLISECONDS); pstm.shutdown(); } @Test public void testStartWidgetUpdaterAfterShutdown() { // Should not throw. final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.shutdown(); pstm.startWidgetUpdater(); } @Test public void testIsWidgetUpdaterActive() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.startWidgetUpdater(); assertTrue(pstm.isWidgetUpdaterActive()); pstm.shutdown(); } @Test public void testCancelWidgetUpdater() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.startWidgetUpdater(); pstm.cancelWidgetUpdater(); assertFalse(pstm.isWidgetUpdaterActive()); pstm.shutdown(); } @Test public void testCancelAllTasksNoTasksStarted() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.cancelAllTasks(); assertFalse(pstm.isPositionSaverActive()); assertFalse(pstm.isWidgetUpdaterActive()); assertFalse(pstm.isSleepTimerActive()); pstm.shutdown(); } @Test @UiThreadTest public void testCancelAllTasksAllTasksStarted() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.startWidgetUpdater(); pstm.startPositionSaver(); pstm.setSleepTimer(100000, false, false); pstm.cancelAllTasks(); assertFalse(pstm.isPositionSaverActive()); assertFalse(pstm.isWidgetUpdaterActive()); assertFalse(pstm.isSleepTimerActive()); pstm.shutdown(); } @Test @UiThreadTest public void testSetSleepTimer() throws InterruptedException { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); final long TIME = 2000; final long TIMEOUT = 2 * TIME; final CountDownLatch countDownLatch = new CountDownLatch(1); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { } @Override public void onSleepTimerAlmostExpired() { } @Override public void onSleepTimerExpired() { if (countDownLatch.getCount() == 0) { fail(); } countDownLatch.countDown(); } @Override public void onSleepTimerReset() { } @Override public void onWidgetUpdaterTick() { } @Override public void onChapterLoaded(Playable media) { } }); pstm.setSleepTimer(TIME, false, false); countDownLatch.await(TIMEOUT, TimeUnit.MILLISECONDS); pstm.shutdown(); } @Test @UiThreadTest public void testDisableSleepTimer() throws InterruptedException { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); final long TIME = 1000; final long TIMEOUT = 2 * TIME; final CountDownLatch countDownLatch = new CountDownLatch(1); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { } @Override public void onSleepTimerAlmostExpired() { } @Override public void onSleepTimerExpired() { fail("Sleeptimer expired"); } @Override public void onSleepTimerReset() { } @Override public void onWidgetUpdaterTick() { } @Override public void onChapterLoaded(Playable media) { } }); pstm.setSleepTimer(TIME, false, false); pstm.disableSleepTimer(); assertFalse(countDownLatch.await(TIMEOUT, TimeUnit.MILLISECONDS)); pstm.shutdown(); } @Test @UiThreadTest public void testIsSleepTimerActivePositive() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.setSleepTimer(10000, false, false); assertTrue(pstm.isSleepTimerActive()); pstm.shutdown(); } @Test @UiThreadTest public void testIsSleepTimerActiveNegative() { final Context c = InstrumentationRegistry.getInstrumentation().getTargetContext(); PlaybackServiceTaskManager pstm = new PlaybackServiceTaskManager(c, defaultPSTM); pstm.setSleepTimer(10000, false, false); pstm.disableSleepTimer(); assertFalse(pstm.isSleepTimerActive()); pstm.shutdown(); } private final PlaybackServiceTaskManager.PSTMCallback defaultPSTM = new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { } @Override public void onSleepTimerAlmostExpired() { } @Override public void onSleepTimerExpired() { } @Override public void onSleepTimerReset() { } @Override public void onWidgetUpdaterTick() { } @Override public void onChapterLoaded(Playable media) { } }; }
package nodomain.freeyourgadget.gadgetbridge.devices.miband; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.widget.TextView; import android.widget.Toast; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.activities.ControlCenter; import nodomain.freeyourgadget.gadgetbridge.activities.DiscoveryActivity; import nodomain.freeyourgadget.gadgetbridge.activities.GBActivity; import nodomain.freeyourgadget.gadgetbridge.devices.DeviceCoordinator; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.util.GB; import nodomain.freeyourgadget.gadgetbridge.util.Prefs; public class MiBandPairingActivity extends GBActivity { private static final Logger LOG = LoggerFactory.getLogger(MiBandPairingActivity.class); private static final int REQ_CODE_USER_SETTINGS = 52; private static final String STATE_MIBAND_ADDRESS = "mibandMacAddress"; private static final long DELAY_AFTER_BONDING = 1000; private TextView message; private boolean isPairing; private String macAddress; private String bondingMacAddress; private final BroadcastReceiver mPairingReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (GBDevice.ACTION_DEVICE_CHANGED.equals(intent.getAction())) { GBDevice device = intent.getParcelableExtra(GBDevice.EXTRA_DEVICE); LOG.debug("pairing activity: device changed: " + device); if (macAddress.equals(device.getAddress()) && device.isInitialized()) { pairingFinished(true); } } } }; private final BroadcastReceiver mBondingReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (bondingMacAddress != null && bondingMacAddress.equals(device.getAddress())) { int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); if (bondState == BluetoothDevice.BOND_BONDED) { LOG.info("Bonded with " + device.getAddress()); bondingMacAddress = null; Looper mainLooper = Looper.getMainLooper(); new Handler(mainLooper).postDelayed(new Runnable() { @Override public void run() { performPair(); } }, DELAY_AFTER_BONDING); } } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mi_band_pairing); message = (TextView) findViewById(R.id.miband_pair_message); Intent intent = getIntent(); macAddress = intent.getStringExtra(DeviceCoordinator.EXTRA_DEVICE_MAC_ADDRESS); if (macAddress == null && savedInstanceState != null) { macAddress = savedInstanceState.getString(STATE_MIBAND_ADDRESS, null); } if (macAddress == null) { Toast.makeText(this, getString(R.string.message_cannot_pair_no_mac), Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, DiscoveryActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); finish(); return; } if (!MiBandCoordinator.hasValidUserInfo()) { Intent userSettingsIntent = new Intent(this, MiBandPreferencesActivity.class); startActivityForResult(userSettingsIntent, REQ_CODE_USER_SETTINGS, null); return; } // already valid user info available, use that and pair startPairing(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_MIBAND_ADDRESS, macAddress); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); macAddress = savedInstanceState.getString(STATE_MIBAND_ADDRESS, macAddress); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // start pairing immediately when we return from the user settings if (requestCode == REQ_CODE_USER_SETTINGS) { if (!MiBandCoordinator.hasValidUserInfo()) { GB.toast(this, getString(R.string.miband_pairing_using_dummy_userdata), Toast.LENGTH_LONG, GB.WARN); } startPairing(); } } @Override protected void onDestroy() { try { // just to be sure, remove the receivers -- might actually be already unregistered LocalBroadcastManager.getInstance(this).unregisterReceiver(mPairingReceiver); unregisterReceiver(mBondingReceiver); } catch (IllegalArgumentException ex) { // already unregistered, ignore } if (isPairing) { stopPairing(); } super.onDestroy(); } private void startPairing() { isPairing = true; message.setText(getString(R.string.miband_pairing, macAddress)); IntentFilter filter = new IntentFilter(GBDevice.ACTION_DEVICE_CHANGED); LocalBroadcastManager.getInstance(this).registerReceiver(mPairingReceiver, filter); filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); registerReceiver(mBondingReceiver, filter); BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress); if (device != null) { performBluetoothPair(device); } else { GB.toast(this, "No such Bluetooth Device: " + macAddress, Toast.LENGTH_LONG, GB.ERROR); } } private void pairingFinished(boolean pairedSuccessfully) { LOG.debug("pairingFinished: " + pairedSuccessfully); if (!isPairing) { // already gone? return; } isPairing = false; LocalBroadcastManager.getInstance(this).unregisterReceiver(mPairingReceiver); unregisterReceiver(mBondingReceiver); Intent intent = new Intent(this, ControlCenter.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } private void stopPairing() { // TODO isPairing = false; } protected void performBluetoothPair(BluetoothDevice device) { int bondState = device.getBondState(); if (bondState == BluetoothDevice.BOND_BONDED) { LOG.info("Already bonded: " + device.getAddress()); performPair(); return; } bondingMacAddress = device.getAddress(); if (bondState == BluetoothDevice.BOND_BONDING) { GB.toast(this, "Bonding in progress: " + bondingMacAddress, Toast.LENGTH_LONG, GB.INFO); return; } GB.toast(this, "Creating bond with" + bondingMacAddress, Toast.LENGTH_LONG, GB.INFO); if (!device.createBond()) { GB.toast(this, "Unable to pair with " + bondingMacAddress, Toast.LENGTH_LONG, GB.ERROR); } } private void performPair() { GBApplication.deviceService().connect(macAddress, true); } }
package com.microsoft.applicationinsights.internal; import android.annotation.TargetApi; import android.os.AsyncTask; import android.os.Build; import com.microsoft.applicationinsights.ApplicationInsights; import com.microsoft.applicationinsights.internal.logging.InternalLogging; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Locale; import java.util.TimerTask; import java.util.zip.GZIPOutputStream; /** * This singleton class sends data to the endpoint. */ public class Sender { private static final String TAG = "Sender"; /** * Volatile boolean for double checked synchronize block. */ private static volatile boolean isSenderLoaded = false; /** * Synchronization LOCK for setting static config. */ private static final Object LOCK = new Object(); /** * The configuration for this sender. */ protected final TelemetryConfig config; /** * The shared Sender instance. */ private static Sender instance; private HashMap<String, TimerTask> currentTasks = new HashMap<>(10); /** * Restrict access to the default constructor */ protected Sender(TelemetryConfig config) { this.config = config; } /** * Initialize the INSTANCE of sender. */ protected static void initialize() { // note: isSenderLoaded must be volatile for the double-checked LOCK to work if (!Sender.isSenderLoaded) { synchronized (Sender.LOCK) { if (!Sender.isSenderLoaded) { Sender.isSenderLoaded = true; Sender.instance = new Sender(new TelemetryConfig()); } } } } /** * @return the INSTANCE of the sender calls initialize before that. */ public static Sender getInstance() { initialize(); if (Sender.instance == null) { InternalLogging.error(TAG, "getInstance was called before initialization"); } return Sender.instance; } public void sendDataOnAppStart() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { send(); return null; } }.execute(); } public void send() { if(runningRequestCount() < 10) { // Send the persisted data Persistence persistence = Persistence.getInstance(); if (persistence != null) { File fileToSend = persistence.nextAvailableFile(); if(fileToSend != null) { String persistedData = persistence.load(fileToSend); if (!persistedData.isEmpty()) { InternalLogging.info(TAG, "sending persisted data", persistedData); SendingTask sendingTask = new SendingTask(persistedData, fileToSend); this.addToRunning(fileToSend.toString(), sendingTask); sendingTask.run(); //TODO add comment for this Thread sendingThread = new Thread(sendingTask); sendingThread.setDaemon(false); }else{ persistence.deleteFile(fileToSend); send(); } } } } else { InternalLogging.info(TAG, "We have already 10 pending reguests", ""); } } private void addToRunning(String key, SendingTask task) { synchronized (Sender.LOCK) { this.currentTasks.put(key, task); } } private void removeFromRunning(String key) { synchronized (Sender.LOCK) { this.currentTasks.remove(key); } } private int runningRequestCount() { synchronized (Sender.LOCK) { return getInstance().currentTasks.size(); } } /** * Handler for the http response from the sender * * @param connection a connection containing a response * @param responseCode the response code from the connection * @param payload the payload which generated this response * @return null if the request was successful, the server response otherwise */ protected String onResponse(HttpURLConnection connection, int responseCode, String payload, File fileToSend) { this.removeFromRunning(fileToSend.toString()); StringBuilder builder = new StringBuilder(); InternalLogging.info(TAG, "response code", Integer.toString(responseCode)); boolean isExpected = ((responseCode > 199) && (responseCode < 203)); boolean isRecoverableError = (responseCode == 429) || (responseCode == 408) || (responseCode == 500) || (responseCode == 503) || (responseCode == 511); boolean deleteFile = isExpected || !isRecoverableError; // If this was expected and developer mode is enabled, read the response if(isExpected) { this.onExpected(connection, builder, fileToSend); this.send(); } if(deleteFile) { Persistence persistence = Persistence.getInstance(); if(persistence != null) { persistence.deleteFile(fileToSend); } } // If there was a server issue, flush the data if (isRecoverableError) { this.onRecoverable(payload, fileToSend); } // If it isn't the usual success code (200), log the response from the server. if (!isExpected) { this.onUnexpected(connection, responseCode, builder); } return builder.toString(); } /** * Process the expected response. If {code:TelemetryChannelConfig.isDeveloperMode}, read the * response and log it. * @param connection a connection containing a response * @param builder a string builder for storing the response * @param fileToSend */ protected void onExpected(HttpURLConnection connection, StringBuilder builder, File fileToSend) { if (ApplicationInsights.isDeveloperMode()) { this.readResponse(connection, builder); } } /** * @param connection a connection containing a response * @param responseCode the response code from the connection * @param builder a string builder for storing the response */ protected void onUnexpected(HttpURLConnection connection, int responseCode, StringBuilder builder) { String message = String.format(Locale.ROOT, "Unexpected response code: %d", responseCode); builder.append(message); builder.append("\n"); // log the unexpected response InternalLogging.warn(TAG, message); // attempt to read the response stream this.readResponse(connection, builder); } /** * Writes the payload to disk if the response code indicates that the server or network caused * the failure instead of the client. * * @param payload the payload which generated this response * @param fileToSend */ protected void onRecoverable(String payload, File fileToSend) { InternalLogging.info(TAG, "Server error, persisting data", payload); Persistence persistence = Persistence.getInstance(); if (persistence != null) { persistence.makeAvailable(fileToSend); } } /** * Reads the response from a connection. * * @param connection the connection which will read the response * @param builder a string builder for storing the response */ private void readResponse(HttpURLConnection connection, StringBuilder builder) { BufferedReader reader = null; try { InputStream inputStream = connection.getErrorStream(); if (inputStream == null) { inputStream = connection.getInputStream(); } if (inputStream != null) { InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8"); reader = new BufferedReader(streamReader); String responseLine = reader.readLine(); while (responseLine != null) { builder.append(responseLine); responseLine = reader.readLine(); } } else { builder.append(connection.getResponseMessage()); } } catch (IOException e) { InternalLogging.error(TAG, e.toString()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { InternalLogging.error(TAG, e.toString()); } } } } /** * Gets a writer from the connection stream (allows for test hooks into the write stream) * * @param connection the connection to which the stream will be flushed * @return a writer for the given connection stream * @throws java.io.IOException */ @TargetApi(Build.VERSION_CODES.KITKAT) protected Writer getWriter(HttpURLConnection connection) throws IOException { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // GZIP if we are running SDK 19 or higher connection.addRequestProperty("Content-Encoding", "gzip"); connection.setRequestProperty("Content-Type", "application/json"); GZIPOutputStream gzip = new GZIPOutputStream(connection.getOutputStream(), true); return new OutputStreamWriter(gzip); } else { // no GZIP for older devices return new OutputStreamWriter(connection.getOutputStream()); } } private class SendingTask extends TimerTask { private String payload; private File fileToSend; public SendingTask(String payload, File fileToSend) { this.payload = payload; this.fileToSend = fileToSend; } @Override public void run() { if (this.payload != null) { try { InternalLogging.info(TAG, "sending persisted data", payload); this.sendRequestWithPayload(payload); } catch (IOException e) { InternalLogging.error(TAG, e.toString()); } } } protected void sendRequestWithPayload(String payload) throws IOException { Writer writer = null; URL url = new URL(config.getEndpointUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(config.getSenderReadTimeout()); connection.setConnectTimeout(config.getSenderConnectTimeout()); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); try { InternalLogging.info(TAG, "writing payload", payload); writer = getWriter(connection); writer.write(payload); writer.flush(); // Starts the query connection.connect(); // read the response code while we're ready to catch the IO exception int responseCode = connection.getResponseCode(); // process the response onResponse(connection, responseCode, payload, fileToSend); } catch (IOException e) { InternalLogging.error(TAG, e.toString()); Persistence persistence = Persistence.getInstance(); if (persistence != null) { persistence.makeAvailable(fileToSend); //send again later } } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // no-op } } } } } }
package com.axelor.apps.businessproject.web; import com.axelor.apps.ReportFactory; import com.axelor.apps.base.db.Partner; import com.axelor.apps.base.db.repo.PriceListRepository; import com.axelor.apps.base.service.PartnerPriceListService; import com.axelor.apps.businessproject.db.InvoicingProject; import com.axelor.apps.businessproject.report.IReport; import com.axelor.apps.businessproject.service.InvoicingProjectService; import com.axelor.apps.businessproject.service.ProjectBusinessService; import com.axelor.apps.project.db.Project; import com.axelor.apps.project.db.repo.ProjectRepository; import com.axelor.apps.purchase.db.PurchaseOrder; import com.axelor.apps.report.engine.ReportSettings; import com.axelor.apps.sale.db.SaleOrder; import com.axelor.exception.AxelorException; import com.axelor.exception.service.TraceBackService; import com.axelor.i18n.I18n; import com.axelor.inject.Beans; import com.axelor.meta.schema.actions.ActionView; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import java.lang.invoke.MethodHandles; import java.math.BigDecimal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class ProjectController { private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Inject private ProjectBusinessService projectBusinessService; @Inject private InvoicingProjectService invoicingProjectService; @Inject private ProjectRepository projectRepo; public void generateQuotation(ActionRequest request, ActionResponse response) { try { Project project = request.getContext().asType(Project.class); SaleOrder order = projectBusinessService.generateQuotation(project); response.setView( ActionView.define("Sale Order") .model(SaleOrder.class.getName()) .add("form", "sale-order-form") .context("_showRecord", String.valueOf(order.getId())) .map()); } catch (Exception e) { TraceBackService.trace(response, e); } } public void generatePurchaseQuotation(ActionRequest request, ActionResponse response) { Project project = request.getContext().asType(Project.class); if (project.getId() != null) { response.setView( ActionView.define("Purchase Order") .model(PurchaseOrder.class.getName()) .add("form", "purchase-order-form") .add("grid", "purchase-order-quotation-grid") .context("_project", projectRepo.find(project.getId())) .map()); } } public void printProject(ActionRequest request, ActionResponse response) throws AxelorException { Project project = request.getContext().asType(Project.class); String name = I18n.get("Project") + " " + project.getCode(); String fileLink = ReportFactory.createReport(IReport.PROJECT, name + "-${date}") .addParam("ProjectId", project.getId()) .addParam("Locale", ReportSettings.getPrintingLocale(null)) .toAttach(project) .generate() .getFileLink(); logger.debug("Printing " + name); response.setView(ActionView.define(name).add("html", fileLink).map()); } // TODO: Duration is removed. Have to change calcuation public void computeProgress(ActionRequest request, ActionResponse response) { // Project project = request.getContext().asType(Project.class); BigDecimal duration = BigDecimal.ZERO; // if (BigDecimal.ZERO.compareTo(project.getDuration()) != 0) { // duration = // project // .getTimeSpent() // .add(project.getLeadDelay()) // .divide(project.getDuration(), 2, java.math.RoundingMode.HALF_UP) // .multiply(new BigDecimal(100)); if (duration.compareTo(BigDecimal.ZERO) == -1 || duration.compareTo(new BigDecimal(100)) == 1) { duration = BigDecimal.ZERO; } response.setValue("progress", duration); } public void countToInvoice(ActionRequest request, ActionResponse response) { Project project = request.getContext().asType(Project.class); int toInvoiceCount = 0; if (project.getId() != null) { toInvoiceCount = invoicingProjectService.countToInvoice(project); } response.setValue("$toInvoiceCounter", toInvoiceCount); } public void showInvoicingProjects(ActionRequest request, ActionResponse response) { Project project = request.getContext().asType(Project.class); project = Beans.get(ProjectRepository.class).find(project.getId()); response.setView( ActionView.define("Invoice Buisness Project") .model(InvoicingProject.class.getName()) .add("form", "invoicing-project-form") .param("forceEdit", "true") .param("show-toolbar", "false") .context("_project", project) .map()); } public void printPlannifAndCost(ActionRequest request, ActionResponse response) throws AxelorException { Project project = request.getContext().asType(Project.class); String name = I18n.get("Planification and costs"); if (project.getCode() != null) { name += " (" + project.getCode() + ")"; } String fileLink = ReportFactory.createReport(IReport.PLANNIF_AND_COST, name) .addParam("ProjectId", project.getId()) .addParam("Locale", ReportSettings.getPrintingLocale(null)) .toAttach(project) .generate() .getFileLink(); response.setView(ActionView.define(name).add("html", fileLink).map()); } public void getPartnerData(ActionRequest request, ActionResponse response) { Project project = request.getContext().asType(Project.class); Partner partner = project.getClientPartner(); if (partner != null) { response.setValue("currency", partner.getCurrency()); response.setValue( "priceList", project.getClientPartner() != null ? Beans.get(PartnerPriceListService.class) .getDefaultPriceList(project.getClientPartner(), PriceListRepository.TYPE_SALE) : null); } } }
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.bll.utils.VmDeviceUtils; import org.ovirt.engine.core.bll.validator.LocalizedVmStatus; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.AttachDettachVmDiskParameters; import org.ovirt.engine.core.common.businessentities.Disk; import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType; import org.ovirt.engine.core.common.businessentities.DiskImage; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceId; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.compat.Guid; public class DetachDiskFromVmCommand<T extends AttachDettachVmDiskParameters> extends AbstractDiskVmCommand<T> { private Disk disk; private VmDevice vmDevice; public DetachDiskFromVmCommand(T parameters) { super(parameters); } @Override protected boolean canDoAction() { boolean retValue = isVmExist(); if (retValue) { retValue = canRunActionOnNonManagedVm(); } if (retValue && getVm().getStatus() != VMStatus.Up && getVm().getStatus() != VMStatus.Down) { retValue = failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(getVm().getStatus())); } if (retValue) { disk = loadDisk((Guid) getParameters().getEntityInfo().getId()); retValue = isDiskExist(disk); } if (retValue) { vmDevice = getVmDeviceDao().get(new VmDeviceId(disk.getId(), getVmId())); if (vmDevice == null) { retValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_ALREADY_DETACHED); } if (retValue && vmDevice.getSnapshotId() != null) { disk = loadDiskFromSnapshot(disk.getId(), vmDevice.getSnapshotId()); } } if (vmDevice.getIsPlugged()) { if (retValue && Boolean.TRUE.equals(getParameters().isPlugUnPlug()) && getVm().getStatus() != VMStatus.Down) { retValue = isInterfaceSupportedForPlugUnPlug(disk); } if (retValue && Boolean.FALSE.equals(getParameters().isPlugUnPlug()) && getVm().getStatus() != VMStatus.Down) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_NOT_DOWN); retValue = false; } } // Check if disk has no snapshots before detaching it. if (retValue && DiskStorageType.IMAGE == disk.getDiskStorageType()) { // A "regular" disk cannot be detached if it's part of the vm snapshots // when a disk snapshot is being detached, it will always be part of snapshots - but of it's "original" vm, // therefore for attached disk snapshot it shouldn't be checked whether it has snapshots or not. if (vmDevice.getSnapshotId() == null && getDiskImageDao().getAllSnapshotsForImageGroup(disk.getId()).size() > 1) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_DETACH_DISK_WITH_SNAPSHOT); retValue = false; } } return retValue; } @Override protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__DETACH_ACTION_TO); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK); } @Override protected void executeVmCommand() { if (diskShouldBeUnPlugged()) { performPlugCommand(VDSCommandType.HotUnPlugDisk, disk, vmDevice); } getVmDeviceDao().remove(vmDevice.getId()); if (!disk.isDiskSnapshot() && DiskStorageType.IMAGE == disk.getDiskStorageType()) { // clears snapshot ID getImageDao().updateImageVmSnapshotId(((DiskImage) disk).getImageId(), null); } // update cached image VmHandler.updateDisksFromDb(getVm()); // update vm device boot order VmDeviceUtils.updateBootOrderInVmDeviceAndStoreToDB(getVm().getStaticData()); setSucceeded(true); } private boolean diskShouldBeUnPlugged() { return Boolean.TRUE.equals(getParameters().isPlugUnPlug() && vmDevice.getIsPlugged() && getVm().getStatus() != VMStatus.Down); } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.USER_DETACH_DISK_FROM_VM : AuditLogType.USER_FAILED_DETACH_DISK_FROM_VM; } @Override public String getDiskAlias() { return disk.getDiskAlias(); } }
package org.ovirt.engine.core.bll.adbroker; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; public class DefaultRootDSE implements RootDSE { private String defaultNamingContext; public DefaultRootDSE(Attributes rootDseRecords) throws NamingException { Attribute namingContexts = rootDseRecords.get(DefaultRootDSEAttributes.namingContexts.name()); if ( namingContexts != null ) { this.defaultNamingContext = namingContexts.get(0).toString(); } } @Override public void setDefaultNamingContext(String defaultNamingContext) { this.defaultNamingContext = defaultNamingContext; } @Override public String getDefaultNamingContext() { return defaultNamingContext; } }
package org.ovirt.engine.core.utils.kerberos; import java.net.URI; import java.security.PrivilegedAction; import java.util.Hashtable; import javax.naming.AuthenticationException; import javax.naming.CommunicationException; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.apache.log4j.Logger; import org.ovirt.engine.core.ldap.LdapProviderType; import org.ovirt.engine.core.ldap.LdapSRVLocator; import org.ovirt.engine.core.ldap.RootDSEData; import org.ovirt.engine.core.utils.dns.DnsSRVLocator.DnsSRVResult; import org.ovirt.engine.core.utils.ipa.RHDSUserContextMapper; /** * JAAS Privileged action to be run when KerbersUtil successfully authenticates. This action performs ldap query to * retrieve information on the authenticated user and prints the object GUID of that user. */ public class JndiAction implements PrivilegedAction { private String userName; private final String domainName; private LdapProviderType ldapProviderType = LdapProviderType.activeDirectory; private final StringBuffer userGuid; private final static Logger log = Logger.getLogger(JndiAction.class); public JndiAction(String userName, String domainName, StringBuffer userGuid, LdapProviderType ldapProviderType) { this.userName = userName; this.domainName = domainName; this.ldapProviderType = ldapProviderType; this.userGuid = userGuid; } @Override public Object run() { Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put("java.naming.ldap.attributes.binary", "objectGUID"); env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI"); env.put("javax.security.sasl.qop", "auth-conf"); // Send an SRV record DNS query to retrieve all the LDAP servers in the domain LdapSRVLocator locator = new LdapSRVLocator(); DnsSRVResult ldapDnsResult; try { ldapDnsResult = locator.getLdapServers(domainName); } catch (Exception ex) { return KerberosUtils.convertDNSException(ex); } DirContext ctx = null; String currentLdapServer = null; if (ldapDnsResult == null || ldapDnsResult.getNumOfValidAddresses() == 0) { return AuthenticationResult.CANNOT_FIND_LDAP_SERVER_FOR_DOMAIN; } // Goes over all the retrieved LDAP servers for (int counter = 0; counter < ldapDnsResult.getNumOfValidAddresses(); counter++) { String address = ldapDnsResult.getAddresses()[counter]; try { // Constructs an LDAP url in a format of ldap://hostname:port (based on the data in the SRV record // This URL is not enough in order to query for user - as for querying users, we should also provide a // base dn, for example: ldap://hostname:389/DC=abc,DC=com . However, this URL (ldap:hostname:port) // suffices for // getting the rootDSE information, which includes the baseDN. URI uri = locator.constructURI("LDAP", address); env.put(Context.PROVIDER_URL, uri.toString()); ctx = new InitialDirContext(env); // Get the base DN from rootDSE String domainDN = getDomainDN(ctx); if (domainDN != null) { // Append the base DN to the ldap URL in order to construct a full ldap URL (in form of // ldap:hostname:port/baseDN ) to query for the user StringBuilder ldapQueryPath = new StringBuilder(uri.toString()); ldapQueryPath.append("/").append(domainDN); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Adding all the three attributes possible, as RHDS doesn't return the nsUniqueId by default controls.setReturningAttributes(new String[]{"nsUniqueId", "ipaUniqueId","objectGuid","uniqueIdentifier"}); // Added this in order to prevent a warning saying: "the returning obj flag wasn't set, setting it to true" controls.setReturningObjFlag(true); currentLdapServer = ldapQueryPath.toString(); env.put(Context.PROVIDER_URL, currentLdapServer); // Run the LDAP query to get the user ctx = new InitialDirContext(env); NamingEnumeration<SearchResult> answer = executeQuery(ctx, controls, prepareQuery()); while (answer.hasMoreElements()) { // Print the objectGUID for the user String guid = guidFromResults(answer.next()); if (guid == null) { break; } userGuid.append(guid); log.debug("User guid is: " + userGuid.toString()); return AuthenticationResult.OK; } System.out.println("No user in Directory was found for " + userName + ". Trying next LDAP server in list"); } else { System.out.println(InstallerConstants.ERROR_PREFIX + " Failed to query rootDSE in order to get the baseDN. Could not query for user " + userName + " in domain " + domainName); } } catch (CommunicationException ex) { handleCommunicationException(currentLdapServer, address); } catch (AuthenticationException ex) { handleAuthenticationException(ex); } catch (Exception ex) { handleGeneralException(ex); break; } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } // end of loop on addresses return AuthenticationResult.NO_USER_INFORMATION_WAS_FOUND_FOR_USER; } protected void handleGeneralException(Exception ex) { System.out.println("General error has occured" + ex.getMessage()); ex.printStackTrace(); } protected void handleAuthenticationException(AuthenticationException ex) { ex.printStackTrace(); AuthenticationResult result = AuthenticationResult.OTHER; KerberosReturnCodeParser parser = new KerberosReturnCodeParser(); result = parser.parse(ex.toString()); String errorMsg = result.getDetailedMessage().replace("Authentication Failed", "LDAP query Failed"); System.out.println(InstallerConstants.ERROR_PREFIX + errorMsg); log.error("Error from Kerberos: " + ex.getMessage()); } protected void handleCommunicationException(String currentLdapServer, String address) { String communicationFailureReason = null; if (currentLdapServer != null) { communicationFailureReason = "Cannot connect to LDAP URL: " + currentLdapServer; } else { if (address != null) { communicationFailureReason = "Cannot connect to LDAP server " + address; } else { communicationFailureReason = "Error in connectiong to LDAP server. LDAP server URL could not be obtained"; } } System.out.println(communicationFailureReason + ". Trying next LDAP server in list (if exists)"); } private String guidFromResults(SearchResult sr) throws NamingException { String guidString = ""; try { if (ldapProviderType.equals(LdapProviderType.ipa)) { String ipaUniqueId = (String) sr.getAttributes().get("ipaUniqueId").get(); guidString += ipaUniqueId; } else if (ldapProviderType.equals(LdapProviderType.rhds)) { String nsUniqueId = (String) sr.getAttributes().get("nsUniqueId").get(); guidString += RHDSUserContextMapper.getGuidFromNsUniqueId(nsUniqueId); } else if (ldapProviderType.equals(LdapProviderType.itds)) { String uniqueId = (String) sr.getAttributes().get("uniqueIdentifier").get(); guidString += uniqueId; } else { Object objectGuid = sr.getAttributes().get("objectGUID").get(); byte[] guid = (byte[]) objectGuid; guidString += ((new org.ovirt.engine.core.compat.Guid(guid, false)).toString()); } } catch (NullPointerException ne) { System.out.println("LDAP connection successful. But no guid found"); guidString = null; } return guidString; } private String prepareQuery() { String query; if (ldapProviderType.equals(LdapProviderType.ipa)) { userName = userName.split("@")[0]; query = "(&(objectClass=posixAccount)(objectClass=krbPrincipalAux)(uid=" + userName + "))"; } else if (ldapProviderType.equals(LdapProviderType.rhds)) { userName = userName.split("@")[0]; query = "(&(objectClass=person)(uid=" + userName + "))"; } else if (ldapProviderType.equals(LdapProviderType.itds)) { userName = userName.split("@")[0]; query = "(&(objectClass=person)(uid=" + userName + "))"; } else { StringBuilder queryBase = new StringBuilder("(&(sAMAccountType=805306368)("); if (userName.contains("@")) { queryBase.append("userPrincipalName=" + userName); } else { if (userName.length() > 20) { queryBase.append("userPrincipalName=") .append(userName) .append("@") .append(domainName.toUpperCase()); } else { queryBase.append("sAMAccountName=").append(userName); } } query = queryBase.append("))").toString(); } return query; } private NamingEnumeration<SearchResult> executeQuery(DirContext ctx, SearchControls controls, String query) throws NamingException { NamingEnumeration<SearchResult> answer = ctx.search("", query, controls); return answer; } private String getDomainDN(DirContext ctx) throws NamingException { RootDSEData rootDSEData = new RootDSEData(ctx); return rootDSEData.getDomainDN(); } }
package org.ovirt.engine.core.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.junit.Test; import org.ovirt.engine.core.common.interfaces.ErrorTranslator; public class ErrorTranslatorTest { private static final String TEST_KEY_NO_REPLACEMENT = "TEST_KEY_NO_REPLACEMENT"; private static final String TEST_KEY_WITH_REPLACEMENT = "TEST_KEY_WITH_REPLACEMENT"; private static final String FILENAME = "TestAppErrors"; private static final String FILENAME_WITH_SUFFIX = FILENAME + ".properties"; @Test public void testNoStringSubstitutionWithoutSuffix() { doTestNoStringSubstitution(FILENAME); } @Test public void testNoStringSubstitutionWithSuffix() { doTestNoStringSubstitution(FILENAME_WITH_SUFFIX); } private static void doTestNoStringSubstitution(String name) { Locale locale = Locale.ENGLISH; try { Locale.setDefault(Locale.ENGLISH); ErrorTranslator et = new ErrorTranslatorImpl(name); String error = et.TranslateErrorTextSingle(TEST_KEY_NO_REPLACEMENT); assertEquals("String should equal", "VM not found", error); } finally { Locale.setDefault(locale); } } @Test public void testNoStringSubstitutionWithList() { ErrorTranslator et = new ErrorTranslatorImpl(FILENAME); List<String> error = et.TranslateErrorText(Arrays.asList(TEST_KEY_NO_REPLACEMENT)); assertTrue("Size", error.size() == 1); assertEquals("String should equal", "VM not found", error.get(0)); } @Test public void testStringSubstitutionWithList() { ErrorTranslator et = new ErrorTranslatorImpl(FILENAME); List<String> error = et.TranslateErrorText(Arrays.asList(TEST_KEY_WITH_REPLACEMENT, "$action SOMEACTION", "$type SOME Type")); String result = "Cannot SOMEACTION SOME Type. VM's Image doesn't exist."; assertTrue("Size", error.size() == 1); assertEquals("String should equal", result, error.get(0)); } @Test public void testLocaleSpecificWithoutSuffix() { doTestLocaleSpecific(FILENAME); } @Test public void testLocaleSpecificWithSuffix() { doTestLocaleSpecific(FILENAME_WITH_SUFFIX); } private static void doTestLocaleSpecific(String name) { Locale locale = Locale.getDefault(); try { Locale.setDefault(Locale.GERMAN); ErrorTranslator et = new ErrorTranslatorImpl(name); List<String> errors = et.TranslateErrorText(Arrays.asList(TEST_KEY_NO_REPLACEMENT)); assertEquals("Unexpected Size", 1, errors.size()); assertEquals("String should equal", "Desktop nicht gefunden", errors.get(0)); String error = et.TranslateErrorTextSingle(TEST_KEY_NO_REPLACEMENT, Locale.GERMAN); assertEquals("String should equal", "Desktop nicht gefunden", error); } finally { Locale.setDefault(locale); } } @Test public void testLocaleOverrideWithoutSuffix() { doTestLocaleOverride(FILENAME); } @Test public void testLocaleOverrideWithSuffix() { doTestLocaleOverride(FILENAME_WITH_SUFFIX); } private static void doTestLocaleOverride(String name) { ErrorTranslator et = new ErrorTranslatorImpl(name); List<String> errors = et.TranslateErrorText(Arrays.asList(TEST_KEY_NO_REPLACEMENT), Locale.ITALIAN); assertEquals("Unexpected Size", 1, errors.size()); assertEquals("String should equal", "Impossibile trovare il desktop", errors.get(0)); String error = et.TranslateErrorTextSingle(TEST_KEY_NO_REPLACEMENT, Locale.ITALIAN); assertEquals("String should equal", "Impossibile trovare il desktop", error); } }
package gov.nih.nci.caintegrator2.web.action.query; //import gov.nih.nci.caintegrator2.data.StudyHelper; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import gov.nih.nci.caintegrator2.AcegiAuthenticationStub; import gov.nih.nci.caintegrator2.application.arraydata.ReporterTypeEnum; import gov.nih.nci.caintegrator2.application.query.QueryManagementService; import gov.nih.nci.caintegrator2.application.query.QueryManagementServiceStub; import gov.nih.nci.caintegrator2.application.query.ResultTypeEnum; import gov.nih.nci.caintegrator2.application.study.EntityTypeEnum; import gov.nih.nci.caintegrator2.application.workspace.WorkspaceServiceStub; import gov.nih.nci.caintegrator2.domain.annotation.AbstractPermissibleValue; import gov.nih.nci.caintegrator2.domain.annotation.AnnotationDefinition; import gov.nih.nci.caintegrator2.domain.application.StudySubscription; import gov.nih.nci.caintegrator2.domain.translational.Study; import gov.nih.nci.caintegrator2.web.SessionHelper; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import org.acegisecurity.context.SecurityContextHolder; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; public class ManageQueryActionTest { private ManageQueryAction manageQueryAction; // Study objects private static final String selectedRowCriterion = "clinical"; private final QueryManagementService queryManagementService = new QueryManagementServiceStub(); // dummy string array for testing private final String [] selectedAnnotationsArray = {"annotation1", "annotation2"}; private final String [] operatorsArray = {"equals",">"}; private final String [] selectedValuesArray = {"String1", "1.0"}; private final Long [] holdLongArray = {Long.valueOf(12), Long.valueOf(4)}; @Before @SuppressWarnings({"PMD"}) public void setUp() { ApplicationContext context = new ClassPathXmlApplicationContext("query-management-action-test-config.xml", ManageQueryActionTest.class); manageQueryAction = (ManageQueryAction) context.getBean("manageQueryAction"); manageQueryAction.setSelectedRowCriterion(selectedRowCriterion); manageQueryAction.setQueryManagementService(queryManagementService); manageQueryAction.setWorkspaceService(new WorkspaceServiceStub()); setupSession(); // the first time the parameter is null so // confirm that the getter method returns a null or an empty array Long[] emptyLongArray = new Long[0]; assertArrayEquals(null,manageQueryAction.getSelectedAnnotations()); manageQueryAction.setSelectedAnnotations(selectedAnnotationsArray); assertArrayEquals(selectedAnnotationsArray,manageQueryAction.getSelectedAnnotations()); assertArrayEquals(null,manageQueryAction.getSelectedOperators()); manageQueryAction.setSelectedOperators(operatorsArray); assertArrayEquals(operatorsArray,manageQueryAction.getSelectedOperators()); assertArrayEquals(null,manageQueryAction.getSelectedValues()); manageQueryAction.setSelectedValues(selectedValuesArray); assertArrayEquals(selectedValuesArray,manageQueryAction.getSelectedValues()); assertArrayEquals(emptyLongArray,manageQueryAction.getSelectedClinicalAnnotations()); manageQueryAction.setSelectedClinicalAnnotations(holdLongArray); assertArrayEquals(holdLongArray,manageQueryAction.getSelectedClinicalAnnotations()); assertArrayEquals(emptyLongArray,manageQueryAction.getSelectedImageAnnotations()); manageQueryAction.setSelectedImageAnnotations(holdLongArray); assertArrayEquals(holdLongArray,manageQueryAction.getSelectedImageAnnotations()); manageQueryAction.setSelectedRowCriterion(selectedRowCriterion); manageQueryAction.setSelectedAction(""); assertEquals("", manageQueryAction.getSelectedAction()); manageQueryAction.setPageSize(10); assertEquals("", manageQueryAction.getSelectedAction()); } @SuppressWarnings({"PMD", "unchecked"}) private void setupSession() { SecurityContextHolder.getContext().setAuthentication(new AcegiAuthenticationStub()); ActionContext.getContext().setSession(new HashMap<String, Object>()); SessionHelper sessionHelper = SessionHelper.getInstance(); manageQueryAction.setSelectedClinicalAnnotations(holdLongArray); manageQueryAction.setSelectedImageAnnotations(holdLongArray); manageQueryAction.prepare(); assertEquals("criteria", manageQueryAction.getDisplayTab()); StudySubscription studySubscription = new StudySubscription(); studySubscription.setStudy(new Study()); studySubscription.setId(1L); StudySubscription studySubscription2 = new StudySubscription(); studySubscription2.setStudy(new Study()); studySubscription2.setId(2L); sessionHelper.getDisplayableUserWorkspace().getUserWorkspace().getSubscriptionCollection().clear(); sessionHelper.getDisplayableUserWorkspace().getUserWorkspace().getSubscriptionCollection().add(studySubscription); sessionHelper.getDisplayableUserWorkspace().getUserWorkspace().getSubscriptionCollection().add(studySubscription2); sessionHelper.getDisplayableUserWorkspace().setCurrentStudySubscription(studySubscription); manageQueryAction.validate(); manageQueryAction.getManageQueryHelper().setQueryCriteriaRowList(new ArrayList<QueryAnnotationCriteria>()); QueryAnnotationCriteria queryAnnotationCriteria = new QueryAnnotationCriteria(); AnnotationSelection annotationSelection = new AnnotationSelection(); annotationSelection.setAnnotationDefinitions(new HashSet<AnnotationDefinition>()); annotationSelection.getAnnotationDefinitions().add(new AnnotationDefinition()); queryAnnotationCriteria.setAnnotationSelection(annotationSelection); queryAnnotationCriteria.setRowType(EntityTypeEnum.SUBJECT); manageQueryAction.getManageQueryHelper().getQueryCriteriaRowList().add(queryAnnotationCriteria); QueryAnnotationCriteria queryAnnotationCriteria2 = new QueryAnnotationCriteria(); AnnotationSelection annotationSelection2 = new AnnotationSelection(); annotationSelection2.setAnnotationDefinitions(new HashSet<AnnotationDefinition>()); annotationSelection2.getAnnotationDefinitions().add(new AnnotationDefinition()); queryAnnotationCriteria2.setAnnotationSelection(annotationSelection2); queryAnnotationCriteria2.setRowType(EntityTypeEnum.SUBJECT); manageQueryAction.getManageQueryHelper().getQueryCriteriaRowList().add(queryAnnotationCriteria2); } @Test @SuppressWarnings({"PMD"}) public void testExecute() { // test create new query manageQueryAction.setSelectedAction("createNewQuery"); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test edit new query manageQueryAction.setSelectedAction("editQuery"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test execute query manageQueryAction.setSelectedAction("executeQuery"); manageQueryAction.getManageQueryHelper().setResultType(ResultTypeEnum.GENOMIC.getValue()); manageQueryAction.getManageQueryHelper().setReporterType(ReporterTypeEnum.GENE_EXPRESSION_PROBE_SET.getValue()); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test save query manageQueryAction.setSelectedAction("saveQuery"); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test - addition of criteria rows // test - addition of row with non-clinical criterion manageQueryAction.setSelectedRowCriterion("notaclinicalrow"); assertEquals("notaclinicalrow",manageQueryAction.getSelectedRowCriterion()); manageQueryAction.setSelectedAction("addCriterionRow"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test - addition of row with clinical criterion manageQueryAction.setSelectedRowCriterion(selectedRowCriterion); assertEquals(selectedRowCriterion,manageQueryAction.getSelectedRowCriterion()); manageQueryAction.setSelectedAction("addCriterionRow"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); //test - update Annotation Definition Collection<AnnotationDefinition> subjectAnnotationCollection = new ArrayList<AnnotationDefinition>(); AnnotationDefinition definition = new AnnotationDefinition(); definition.setId(1L); definition.setDisplayName("annotation1"); definition.setType("string"); definition.setPermissibleValueCollection(new ArrayList<AbstractPermissibleValue>()); subjectAnnotationCollection.add(definition); definition = new AnnotationDefinition(); definition.setId(2L); definition.setDisplayName("annotation2"); definition.setType("string"); definition.setPermissibleValueCollection(new ArrayList<AbstractPermissibleValue>()); subjectAnnotationCollection.add(definition); StudySubscription studySubscription = new StudySubscription(); studySubscription.setStudy(new Study()); studySubscription.getStudy().setSubjectAnnotationCollection(subjectAnnotationCollection); studySubscription.setId(1L); StudySubscription studySubscription2 = new StudySubscription(); studySubscription2.setStudy(new Study()); studySubscription2.getStudy().setSubjectAnnotationCollection(subjectAnnotationCollection); studySubscription2.setId(2L); SessionHelper sessionHelper = SessionHelper.getInstance(); sessionHelper.getDisplayableUserWorkspace().getUserWorkspace().getSubscriptionCollection().clear(); sessionHelper.getDisplayableUserWorkspace().getUserWorkspace().getSubscriptionCollection().add(studySubscription); sessionHelper.getDisplayableUserWorkspace().getUserWorkspace().getSubscriptionCollection().add(studySubscription2); sessionHelper.getDisplayableUserWorkspace().setCurrentStudySubscription(studySubscription); manageQueryAction.getManageQueryHelper().prepopulateAnnotationSelectLists(studySubscription.getStudy()); manageQueryAction.setSelectedAction("updateAnnotationDefinition"); manageQueryAction.setRowNumber("0"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test removal of row manageQueryAction.setSelectedAction("remove"); manageQueryAction.setRowNumber("0"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test removal of invalid row still returns success (adds error message though) manageQueryAction.setRowNumber("10"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test invalid removal string still returns success (adds error message though) manageQueryAction.setRowNumber("INVALID INT"); manageQueryAction.prepare(); manageQueryAction.validate(); assertEquals(Action.SUCCESS, manageQueryAction.execute()); // test for invalid action manageQueryAction.setSelectedAction(null); assertEquals(Action.ERROR, manageQueryAction.execute()); assertEquals(Action.SUCCESS, manageQueryAction.addCriterionRow()); assertNotNull(manageQueryAction.getQueryManagementService()); } }
package org.apereo.cas.config; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.ldap.UnsupportedAuthenticationMechanismException; import org.apereo.cas.authentication.LdapAuthenticationHandler; import org.apereo.cas.authentication.principal.PrincipalResolver; import org.apereo.cas.authentication.support.DefaultAccountStateHandler; import org.apereo.cas.authentication.support.LdapPasswordPolicyConfiguration; import org.apereo.cas.authentication.support.OptionalWarningAccountStateHandler; import org.apereo.cas.authorization.generator.LdapAuthorizationGenerator; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties; import org.apereo.cas.configuration.support.Beans; import org.apereo.cas.services.ServicesManager; import org.ldaptive.ConnectionFactory; import org.ldaptive.SearchExecutor; import org.ldaptive.auth.Authenticator; import org.ldaptive.auth.FormatDnResolver; import org.ldaptive.auth.PooledBindAuthenticationHandler; import org.ldaptive.auth.PooledCompareAuthenticationHandler; import org.ldaptive.auth.PooledSearchDnResolver; import org.ldaptive.auth.SearchEntryResolver; import org.ldaptive.auth.ext.ActiveDirectoryAuthenticationResponseHandler; import org.ldaptive.auth.ext.EDirectoryAuthenticationResponseHandler; import org.ldaptive.auth.ext.FreeIPAAuthenticationResponseHandler; import org.ldaptive.auth.ext.PasswordExpirationAuthenticationResponseHandler; import org.ldaptive.auth.ext.PasswordPolicyAuthenticationResponseHandler; import org.ldaptive.control.PasswordPolicyControl; import org.pac4j.core.authorization.generator.AuthorizationGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import java.time.Period; import java.util.HashMap; import java.util.Map; /** * This is {@link LdapAuthenticationConfiguration} that attempts to create * relevant authentication handlers for LDAP. * * @author Misagh Moayyed * @since 5.0.0 */ @Configuration("ldapAuthenticationConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class LdapAuthenticationConfiguration { @Autowired(required = false) @Qualifier("ldapAuthorizationGeneratorConnectionFactory") private ConnectionFactory connectionFactory; @Autowired(required = false) @Qualifier("ldapAuthorizationGeneratorUserSearchExecutor") private SearchExecutor userSearchExecutor; @Autowired private CasConfigurationProperties casProperties; @Autowired @Qualifier("personDirectoryPrincipalResolver") private PrincipalResolver personDirectoryPrincipalResolver; @Autowired @Qualifier("authenticationHandlersResolvers") private Map authenticationHandlersResolvers; @Autowired @Qualifier("servicesManager") private ServicesManager servicesManager; @Bean @RefreshScope public AuthorizationGenerator ldapAuthorizationGenerator() { if (connectionFactory != null) { final LdapAuthorizationGenerator gen = new LdapAuthorizationGenerator(this.connectionFactory, this.userSearchExecutor); gen.setAllowMultipleResults(casProperties.getLdapAuthz().isAllowMultipleResults()); gen.setRoleAttribute(casProperties.getLdapAuthz().getRoleAttribute()); gen.setRolePrefix(casProperties.getLdapAuthz().getRolePrefix()); return gen; } return commonProfile -> { throw new UnsupportedAuthenticationMechanismException("Authorization generator not specified"); }; } @PostConstruct public void initLdapAuthenticationHandlers() { casProperties.getAuthn().getLdap().forEach(l -> { if (l.getType() != null) { final LdapAuthenticationHandler handler = new LdapAuthenticationHandler(); handler.setServicesManager(servicesManager); handler.setAdditionalAttributes(l.getAdditionalAttributes()); handler.setAllowMultiplePrincipalAttributeValues(l.isAllowMultiplePrincipalAttributeValues()); handler.setPasswordEncoder(Beans.newPasswordEncoder(l.getPasswordEncoder())); handler.setPrincipalNameTransformer(Beans.newPrincipalNameTransformer(l.getPrincipalTransformation())); final Map<String, String> attributes = new HashMap<>(); l.getPrincipalAttributeList().forEach(a -> attributes.put(a.toString(), a.toString())); attributes.putAll(casProperties.getAuthn().getAttributeRepository().getAttributes()); handler.setPrincipalAttributeMap(attributes); handler.setPrincipalIdAttribute(l.getPrincipalAttributeId()); final Authenticator authenticator = getAuthenticator(l); if (l.getPasswordPolicy().isEnabled()) { final LdapPasswordPolicyConfiguration cfg = new LdapPasswordPolicyConfiguration(l.getPasswordPolicy()); authenticator.setAuthenticationResponseHandlers( new EDirectoryAuthenticationResponseHandler( Period.ofDays(cfg.getPasswordWarningNumberOfDays())), new ActiveDirectoryAuthenticationResponseHandler( Period.ofDays(cfg.getPasswordWarningNumberOfDays()) ), new FreeIPAAuthenticationResponseHandler( Period.ofDays(cfg.getPasswordWarningNumberOfDays()), cfg.getLoginFailures() ), new PasswordPolicyAuthenticationResponseHandler(), new PasswordExpirationAuthenticationResponseHandler()); if (StringUtils.isNotBlank(l.getPasswordPolicy().getWarningAttributeName()) && StringUtils.isNotBlank(l.getPasswordPolicy().getWarningAttributeValue())) { final OptionalWarningAccountStateHandler accountHandler = new OptionalWarningAccountStateHandler(); accountHandler.setDisplayWarningOnMatch(l.getPasswordPolicy().isDisplayWarningOnMatch()); accountHandler.setWarnAttributeName(l.getPasswordPolicy().getWarningAttributeName()); accountHandler.setWarningAttributeValue(l.getPasswordPolicy().getWarningAttributeValue()); accountHandler.setAttributesToErrorMap(l.getPasswordPolicy().getPolicyAttributes()); cfg.setAccountStateHandler(accountHandler); } else { final DefaultAccountStateHandler accountHandler = new DefaultAccountStateHandler(); accountHandler.setAttributesToErrorMap(l.getPasswordPolicy().getPolicyAttributes()); cfg.setAccountStateHandler(accountHandler); } handler.setPasswordPolicyConfiguration(cfg); } handler.setAuthenticator(authenticator); handler.initialize(); if (l.getAdditionalAttributes().isEmpty() && l.getPrincipalAttributeList().isEmpty()) { this.authenticationHandlersResolvers.put(handler, this.personDirectoryPrincipalResolver); } else { this.authenticationHandlersResolvers.put(handler, null); } } }); } private static Authenticator getAuthenticator(final LdapAuthenticationProperties l) { if (l.getType() == LdapAuthenticationProperties.AuthenticationTypes.AD) { return getActiveDirectoryAuthenticator(l); } if (l.getType() == LdapAuthenticationProperties.AuthenticationTypes.DIRECT) { return getDirectBindAuthenticator(l); } return getAuthenticatedOrAnonSearchAuthenticator(l); } private static Authenticator getAuthenticatedOrAnonSearchAuthenticator(final LdapAuthenticationProperties l) { final PooledSearchDnResolver resolver = new PooledSearchDnResolver(); resolver.setBaseDn(l.getBaseDn()); resolver.setSubtreeSearch(l.isSubtreeSearch()); resolver.setAllowMultipleDns(l.isAllowMultipleDns()); resolver.setConnectionFactory(Beans.newPooledConnectionFactory(l)); resolver.setUserFilter(l.getUserFilter()); if (StringUtils.isBlank(l.getPrincipalAttributePassword())) { return new Authenticator(resolver, getPooledBindAuthenticationHandler(l)); } return new Authenticator(resolver, getPooledCustomCompareAuthenticationHandler(l)); } private static Authenticator getDirectBindAuthenticator(final LdapAuthenticationProperties l) { final FormatDnResolver resolver = new FormatDnResolver(l.getBaseDn()); return new Authenticator(resolver, getPooledBindAuthenticationHandler(l)); } private static Authenticator getActiveDirectoryAuthenticator(final LdapAuthenticationProperties l) { final FormatDnResolver resolver = new FormatDnResolver(l.getDnFormat()); final Authenticator authn = new Authenticator(resolver, getPooledBindAuthenticationHandler(l)); final SearchEntryResolver entryResolver = new SearchEntryResolver(); entryResolver.setBaseDn(l.getBaseDn()); entryResolver.setUserFilter(l.getUserFilter()); entryResolver.setSubtreeSearch(l.isSubtreeSearch()); authn.setEntryResolver(entryResolver); return authn; } private static PooledBindAuthenticationHandler getPooledBindAuthenticationHandler(final LdapAuthenticationProperties l) { final PooledBindAuthenticationHandler handler = new PooledBindAuthenticationHandler(Beans.newPooledConnectionFactory(l)); handler.setAuthenticationControls(new PasswordPolicyControl()); return handler; } private static PooledCompareAuthenticationHandler getPooledCustomCompareAuthenticationHandler(final LdapAuthenticationProperties l) { final PooledCompareAuthenticationHandler handler = new PooledCompareAuthenticationHandler( Beans.newPooledConnectionFactory(l)); handler.setPasswordAttribute(l.getPrincipalAttributePassword()); return handler; } }
package hudson.remoting; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.net.HttpURLConnection; import java.net.Socket; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.List; import java.util.Collections; import java.util.logging.Logger; import static java.util.logging.Level.SEVERE; /** * Slave agent engine that proactively connects to Hudson master. * * @author Kohsuke Kawaguchi */ public class Engine extends Thread { /** * Thread pool that sets {@link #CURRENT}. */ private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); public Thread newThread(final Runnable r) { return defaultFactory.newThread(new Runnable() { public void run() { CURRENT.set(Engine.this); r.run(); } }); } }); public final EngineListener listener; private List<URL> candidateUrls; private URL hudsonUrl; private final String secretKey; public final String slaveName; private String credentials; /** * See Main#tunnel in the jnlp-agent module for the details. */ private String tunnel; private boolean noReconnect; public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String slaveName) { this.listener = listener; this.candidateUrls = hudsonUrls; this.secretKey = secretKey; this.slaveName = slaveName; if(candidateUrls.isEmpty()) throw new IllegalArgumentException("No URLs given"); } public URL getHudsonUrl() { return hudsonUrl; } public void setTunnel(String tunnel) { this.tunnel = tunnel; } public void setCredentials(String creds) { this.credentials = creds; } public void setNoReconnect(boolean noReconnect) { this.noReconnect = noReconnect; } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Override public void run() { try { boolean first = true; while(true) { if(first) { first = false; } else { if(noReconnect) return; // exit } listener.status("Locating server among " + candidateUrls); Throwable firstError=null; String port=null; for (URL url : candidateUrls) { String s = url.toExternalForm(); if(!s.endsWith("/")) s+='/'; URL salURL = new URL(s+"tcpSlaveAgentListener/"); // find out the TCP port HttpURLConnection con = (HttpURLConnection)salURL.openConnection(); if (con instanceof HttpURLConnection && credentials != null) { String encoding = new sun.misc.BASE64Encoder().encode(credentials.getBytes()); con.setRequestProperty("Authorization", "Basic " + encoding); } try { try { con.setConnectTimeout(30000); con.setReadTimeout(60000); con.connect(); } catch (IOException x) { if (firstError == null) { firstError = new IOException("Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x); } continue; } port = con.getHeaderField("X-Hudson-JNLP-Port"); if(con.getResponseCode()!=200) { if(firstError==null) firstError = new Exception(salURL+" is invalid: "+con.getResponseCode()+" "+con.getResponseMessage()); continue; } if(port ==null) { if(firstError==null) firstError = new Exception(url+" is not Hudson"); continue; } } finally { con.disconnect(); } // this URL works. From now on, only try this URL hudsonUrl = url; firstError = null; candidateUrls = Collections.singletonList(hudsonUrl); break; } if(firstError!=null) { listener.error(firstError); return; } final Socket s = connect(port); listener.status("Handshaking"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:JNLP-connect"); dos.writeUTF(secretKey); dos.writeUTF(slaveName); BufferedInputStream in = new BufferedInputStream(s.getInputStream()); String greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network? if (!greeting.equals(GREETING_SUCCESS)) { listener.error(new Exception("The server rejected the connection: "+greeting)); Thread.sleep(10*1000); continue; } final Channel channel = new Channel("channel", executor, in, new BufferedOutputStream(s.getOutputStream())); PingThread t = new PingThread(channel) { protected void onDead() { try { if (!channel.isInClosed()) { LOGGER.info("Ping failed. Terminating the socket."); s.close(); } } catch (IOException e) { LOGGER.log(SEVERE, "Failed to terminate the socket", e); } } }; t.start(); listener.status("Connected"); channel.join(); listener.status("Terminated"); t.interrupt(); // make sure the ping thread is terminated listener.onDisconnect(); if(noReconnect) return; // exit // try to connect back to the server every 10 secs. waitForServerToBack(); } } catch (Throwable e) { listener.error(e); } } /** * Read until '\n' and returns it as a string. */ private static String readLine(InputStream in) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (true) { int ch = in.read(); if (ch<0 || ch=='\n') return baos.toString().trim(); // trim off possible '\r' baos.write(ch); } } /** * Connects to TCP slave port, with a few retries. */ private Socket connect(String port) throws IOException, InterruptedException { String host = this.hudsonUrl.getHost(); if(tunnel!=null) { String[] tokens = tunnel.split(":",3); if(tokens.length!=2) throw new IOException("Illegal tunneling parameter: "+tunnel); if(tokens[0].length()>0) host = tokens[0]; if(tokens[1].length()>0) port = tokens[1]; } String msg = "Connecting to " + host + ':' + port; listener.status(msg); int retry = 1; while(true) { try { Socket s = new Socket(host, Integer.parseInt(port)); s.setTcpNoDelay(true); // we'll do buffering by ourselves // set read time out to avoid infinite hang. the time out should be long enough so as not // to interfere with normal operation. the main purpose of this is that when the other peer dies // abruptly, we shouldn't hang forever, and at some point we should notice that the connection // is gone. s.setSoTimeout(30*60*1000); // 30 mins. See PingThread for the ping interval return s; } catch (IOException e) { if(retry++>10) throw (IOException)new IOException("Failed to connect to "+host+':'+port).initCause(e); Thread.sleep(1000*10); listener.status(msg+" (retrying:"+retry+")",e); } } } /** * Waits for the server to come back. */ private void waitForServerToBack() throws InterruptedException { while(true) { Thread.sleep(1000*10); try { HttpURLConnection con = (HttpURLConnection)new URL(hudsonUrl,"tcpSlaveAgentListener/").openConnection(); con.connect(); if(con.getResponseCode()==200) return; } catch (IOException e) { // retry } } } /** * When invoked from within remoted {@link Callable} (that is, * from the thread that carries out the remote requests), * this method returns the {@link Engine} in which the remote operations * run. */ public static Engine current() { return CURRENT.get(); } private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<Engine>(); private static final Logger LOGGER = Logger.getLogger(Engine.class.getName()); public static final String GREETING_SUCCESS = "Welcome"; }
package tools.devnull.boteco.channel.irc; import org.apache.camel.component.irc.IrcMessage; import org.schwering.irc.lib.IRCUser; import tools.devnull.boteco.Channel; import tools.devnull.boteco.Command; import tools.devnull.boteco.CommandExtractor; import tools.devnull.boteco.ServiceLocator; import tools.devnull.boteco.message.IncomeMessage; import tools.devnull.boteco.message.MessageSender; import tools.devnull.boteco.message.Sender; /** * An abstraction of an IRC message. */ public class IrcIncomeMessage implements IncomeMessage { private static final long serialVersionUID = -4838114200533219628L; private final Channel channel = new IrcChannel(); private final CommandExtractor commandExtractor; private final ServiceLocator serviceLocator; private final String message; private final Sender sender; private final String target; public IrcIncomeMessage(IrcMessage income, CommandExtractor commandExtractor, ServiceLocator serviceLocator) { this.commandExtractor = commandExtractor; this.message = income.getMessage(); this.sender = new IrcSender(income.getUser()); this.target = income.getTarget(); this.serviceLocator = serviceLocator; } @Override public Channel channel() { return channel; } @Override public String content() { return message; } @Override public Sender sender() { return this.sender; } @Override public String target() { return target; } @Override public boolean isPrivate() { return !isGroup(); } @Override public boolean isGroup() { return target().startsWith(" } @Override public boolean hasCommand() { return commandExtractor.isCommand(this); } @Override public Command command() { return commandExtractor.extract(this); } @Override public void reply(String content) { if (isPrivate()) { replySender(content); } else { send(target(), content); } } @Override public void replySender(String content) { send(sender.mention(), content); } private void send(String target, String content) { serviceLocator.locate(MessageSender.class).send(content).to(target).through(channel().id()); } private static class IrcSender implements Sender { private static final long serialVersionUID = 6728222816835888595L; private final String id; private final String name; private final String username; private final String nickname; private IrcSender(IRCUser user) { this.id = String.format("%s:%s", user.getHost(), user.getNick()); this.name = user.getUsername(); // IRCUser don't have this so use the username this.username = user.getUsername(); this.nickname = user.getNick(); } @Override public String id() { return id; } @Override public String name() { return name; } @Override public String username() { return username; } @Override public String mention() { return nickname; } @Override public String toString() { return mention(); } } }
package gov.nih.nci.iso21090.grid.dto.transform.iso; import gov.nih.nci.iso21090.Ad; import gov.nih.nci.iso21090.DSet; import gov.nih.nci.iso21090.grid.dto.transform.AbstractTransformer; import gov.nih.nci.iso21090.grid.dto.transform.DtoTransformException; import gov.nih.nci.iso21090.grid.dto.transform.Transformer; import java.util.HashSet; import java.util.List; import java.util.Set; //import org.iso._21090.Ad; import org.iso._21090.DSetAd; import org.iso._21090.NullFlavor; /** * Transforms sets of addresses. */ @SuppressWarnings("PMD.CyclomaticComplexity") public final class DSETADTransformer extends AbstractTransformer<DSetAd, DSet<gov.nih.nci.iso21090.Ad>> implements Transformer<DSetAd, DSet<gov.nih.nci.iso21090.Ad>> { /** * Public transformer instance. */ public static final DSETADTransformer INSTANCE = new DSETADTransformer(); private DSETADTransformer() { } /** * {@inheritDoc} */ public DSetAd toXml(DSet<Ad> input) { DSetAd x = new DSetAd(); if (input != null && input.getItem() != null) { Set<Ad> sItem = input.getItem(); List<org.iso._21090.Ad> tItem = x.getItems(); for (Ad ad : sItem) { org.iso._21090.Ad cur = ADTransformer.INSTANCE.toXml(ad); // XSD rule: all elements of set must be non-null if (!(cur == null || cur.getNullFlavor() != null)) { tItem.add(cur); } } } if (x.getItems().isEmpty()) { x.setNullFlavor(NullFlavor.NI); } return x; } /** * {@inheritDoc} */ public DSet<Ad> toDto(DSetAd input) throws DtoTransformException{ if (input == null || input.getNullFlavor() != null) { return null; } DSet<Ad> x = new DSet<Ad>(); x.setItem(new HashSet<Ad>()); List<org.iso._21090.Ad> sItem = input.getItems(); Set<Ad> tItem = x.getItem(); for (org.iso._21090.Ad ad : sItem) { tItem.add(ADTransformer.INSTANCE.toDto(ad)); } return x; } /** * {@inheritDoc} */ public DSetAd[] createXmlArray(int size) throws DtoTransformException { return new DSetAd[size]; } }
package edu.duke.cabig.c3pr.web.study; import edu.duke.cabig.c3pr.dao.HealthcareSiteDao; import edu.duke.cabig.c3pr.dao.HealthcareSiteInvestigatorDao; import edu.duke.cabig.c3pr.dao.ResearchStaffDao; import edu.duke.cabig.c3pr.domain.HealthcareSite; import edu.duke.cabig.c3pr.domain.validator.StudyValidator; import edu.duke.cabig.c3pr.utils.ConfigurationProperty; import gov.nih.nci.cabig.ctms.web.tabs.StaticTabConfigurer; import org.easymock.EasyMock; import static org.easymock.EasyMock.expect; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author kherm manav.kher@semanticbits.com */ public class CreateStudyControllerTest extends AbstractStudyControllerTest { private edu.duke.cabig.c3pr.web.study.CreateStudyController controller; private HealthCareSiteDaoMock healthcareSiteDao; private HealthcareSiteInvestigatorDao healthcareSiteInvestigatorDao; private ResearchStaffDao researchStaffDao; private StudyValidator studyValidator; private ConfigurationProperty configProperty; protected void setUp() throws Exception { super.setUp(); configProperty = registerMockFor(ConfigurationProperty.class); EasyMock.expect(configProperty.getMap()).andReturn(Collections.emptyMap()).anyTimes(); controller = new CreateStudyController() { @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { //do nothing } }; controller.setStudyDao(studyDao); //setup controller healthcareSiteDao = registerMockFor(HealthCareSiteDaoMock.class); controller.setHealthcareSiteDao(healthcareSiteDao); healthcareSiteInvestigatorDao = registerDaoMockFor(HealthcareSiteInvestigatorDao.class); controller.setHealthcareSiteInvestigatorDao(healthcareSiteInvestigatorDao); researchStaffDao = registerDaoMockFor(ResearchStaffDao.class); controller.setResearchStaffDao(researchStaffDao); controller.setStudyService(studyService); studyValidator = registerMockFor(StudyValidator.class); controller.setStudyValidator(studyValidator); StaticTabConfigurer tabConfigurer = new StaticTabConfigurer(healthcareSiteDao); tabConfigurer.addBean("configurationProperty", configProperty); controller.setTabConfigurer(tabConfigurer); } public void testViewOnGoodSubmit() throws Exception { replayMocks(); ModelAndView mv = controller.handleRequest(request, response); verifyMocks(); assertEquals("study/study_details", mv.getViewName()); } public void testPostAndReturnCommand() throws Exception { request.setMethod("POST"); expect(studyService.merge(command)).andReturn(null); replayMocks(); ModelAndView mv = controller.processFinish(request, response, command, errors); verifyMocks(); Object command = mv.getModel().get("command"); assertNotNull("Command not present in model: " + mv.getModel(), command); } public class HealthCareSiteDaoMock extends HealthcareSiteDao { public List<HealthcareSite> getAll() { List list = new ArrayList(); return list; } } }
package org.torquebox.rails.deployers; import java.io.IOException; import java.io.File; import java.io.Closeable; import org.jboss.deployers.spi.DeploymentException; import org.jboss.deployers.spi.deployer.DeploymentStages; import org.jboss.deployers.spi.deployer.helpers.AbstractDeployer; import org.jboss.deployers.structure.spi.DeploymentUnit; import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VFS; /** * Ensure that log files generated by rails packaged deployments end * up somewhere reasonable, * e.g. JBOSS_HOME/server/default/log/app.rails, because they can't be * written to the deployed archive. */ public class RailsLogFileDeployer extends AbstractDeployer { static final String ATTACHMENT_NAME = "open log dir handle"; public RailsLogFileDeployer() { setStage(DeploymentStages.PARSE ); } public void deploy(DeploymentUnit unit) throws DeploymentException { if ( unit instanceof VFSDeploymentUnit && unit.getName().endsWith( ".rails" )) { deploy( (VFSDeploymentUnit) unit ); } } public void deploy(VFSDeploymentUnit unit) throws DeploymentException { VirtualFile logDir = unit.getRoot().getChild( "log" ); try { File writeableLogDir = new File( System.getProperty( "jboss.server.log.dir" ) + "/" + unit.getSimpleName() ); writeableLogDir.mkdirs(); Closeable mount = VFS.mountReal(writeableLogDir, logDir); log.warn("Set Rails log directory to "+writeableLogDir.getCanonicalPath()); unit.addAttachment( ATTACHMENT_NAME, mount, Closeable.class ); } catch (Exception e) { throw new DeploymentException( e ); } } public void undeploy(DeploymentUnit unit) { if ( unit.getName().endsWith( ".rails" )) { Closeable mount = unit.getAttachment(ATTACHMENT_NAME, Closeable.class); if (mount != null) { log.info("Closing virtual log directory for "+unit.getSimpleName() ); try { mount.close(); } catch (IOException ignored) {} } } } }
package com.yahoo.vespa.config.server.zookeeper; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Collections; import java.util.Optional; import java.util.regex.Pattern; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.provision.Flavor; import com.yahoo.config.provision.HostSpec; import com.yahoo.config.provision.NodeFlavors; import com.yahoo.config.provision.ProvisionInfo; import com.yahoo.config.provision.Version; import com.yahoo.config.provisioning.FlavorsConfig; import com.yahoo.path.Path; import com.yahoo.text.Utf8; import com.yahoo.vespa.config.server.TestWithCurator; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.yahoo.io.IOUtils; public class ZKApplicationPackageTest extends TestWithCurator { private static final String APP = "src/test/apps/zkapp"; private static final String TEST_FLAVOR_NAME = "test-flavor"; private static final Optional<Flavor> TEST_FLAVOR = new MockNodeFlavors().getFlavor(TEST_FLAVOR_NAME); private static final ProvisionInfo provisionInfo = ProvisionInfo.withHosts( Collections.singleton(new HostSpec("foo.yahoo.com", Collections.emptyList(), TEST_FLAVOR, Optional.empty()))); @Rule public TemporaryFolder tmpDir = new TemporaryFolder(); @Test public void testBasicZKFeed() throws IOException { feed(configCurator, new File(APP)); ZKApplicationPackage zkApp = new ZKApplicationPackage(configCurator, Path.fromString("/0"), Optional.of(new MockNodeFlavors())); assertTrue(Pattern.compile(".*<slobroks>.*",Pattern.MULTILINE+Pattern.DOTALL).matcher(IOUtils.readAll(zkApp.getServices())).matches()); assertTrue(Pattern.compile(".*<alias>.*",Pattern.MULTILINE+Pattern.DOTALL).matcher(IOUtils.readAll(zkApp.getHosts())).matches()); assertTrue(Pattern.compile(".*<slobroks>.*",Pattern.MULTILINE+Pattern.DOTALL).matcher(IOUtils.readAll(zkApp.getFile(Path.fromString("services.xml")).createReader())).matches()); DeployState deployState = new DeployState.Builder().applicationPackage(zkApp).build(); assertEquals(deployState.getSearchDefinitions().size(), 5); assertEquals(zkApp.searchDefinitionContents().size(), 5); assertEquals(IOUtils.readAll(zkApp.getRankingExpression("foo.expression")), "foo()+1\n"); assertEquals(zkApp.getFiles(Path.fromString(""), "xml").size(), 3); assertEquals(zkApp.getFileReference(Path.fromString("components/file.txt")).getAbsolutePath(), "/home/vespa/test/file.txt"); try (Reader foo = zkApp.getFile(Path.fromString("files/foo.json")).createReader()) { assertEquals(IOUtils.readAll(foo), "foo : foo\n"); } try (Reader bar = zkApp.getFile(Path.fromString("files/sub/bar.json")).createReader()) { assertEquals(IOUtils.readAll(bar), "bar : bar\n"); } assertTrue(zkApp.getFile(Path.createRoot()).exists()); assertTrue(zkApp.getFile(Path.createRoot()).isDirectory()); Version goodVersion = Version.fromIntValues(3, 0, 0); assertTrue(zkApp.getFileRegistryMap().containsKey(goodVersion)); assertFalse(zkApp.getFileRegistryMap().containsKey(Version.fromIntValues(0, 0, 0))); assertThat(zkApp.getFileRegistryMap().get(goodVersion).fileSourceHost(), is("dummyfiles")); assertTrue(zkApp.getProvisionInfoMap().containsKey(goodVersion)); ProvisionInfo readInfo = zkApp.getProvisionInfoMap().get(goodVersion); assertThat(Utf8.toString(readInfo.toJson()), is(Utf8.toString(provisionInfo.toJson()))); assertThat(readInfo.getHosts().iterator().next().flavor(), is(TEST_FLAVOR)); assertTrue(zkApp.getDeployment().isPresent()); assertThat(DeploymentSpec.fromXml(zkApp.getDeployment().get()).globalServiceId().get(), is("mydisc")); } private void feed(ConfigCurator zk, File dirToFeed) throws IOException { assertTrue(dirToFeed.isDirectory()); zk.feedZooKeeper(dirToFeed, "/0" + ConfigCurator.USERAPP_ZK_SUBPATH, null, true); String metaData = "{\"deploy\":{\"user\":\"foo\",\"from\":\"bar\",\"timestamp\":1},\"application\":{\"name\":\"foo\",\"checksum\":\"abc\",\"generation\":4,\"previousActiveGeneration\":3}}"; zk.putData("/0", ConfigCurator.META_ZK_PATH, metaData); zk.putData("/0/" + ZKApplicationPackage.fileRegistryNode + "/3.0.0", "dummyfiles"); zk.putData("/0/" + ZKApplicationPackage.allocatedHostsNode + "/3.0.0", provisionInfo.toJson()); } private static class MockNodeFlavors extends NodeFlavors{ MockNodeFlavors() { super(flavorsConfig()); } private static FlavorsConfig flavorsConfig() { return new FlavorsConfig(new FlavorsConfig.Builder() .flavor(new FlavorsConfig.Flavor.Builder().name(TEST_FLAVOR_NAME)) ); } } }
package com.peterphi.configuration.service.git; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.peterphi.std.guice.config.rest.types.ConfigPropertyData; import com.peterphi.std.guice.config.rest.types.ConfigPropertyValue; import com.peterphi.std.io.FileHelper; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.RemoteAddCommand; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.merge.MergeStrategy; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.treewalk.TreeWalk; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class RepoHelper { public static final String KEY_INCLUDE = "include"; public static final String KEY_INCLUDE_SHALLOW = "shallow-include"; private static Cache<String, Map<String, Map<String, ConfigPropertyValue>>> COMMIT_CACHE = CacheBuilder.newBuilder() .maximumSize(8) .build(); public static RevCommit resolve(final Repository repo, final String ref) throws IOException { return new RevWalk(repo).parseCommit(repo.resolve(ref)); } public static ConfigPropertyData read(final Repository repo, final String ref, final String path) { try { return read(repo, resolve(repo, ref), path); } catch (IOException e) { throw new RuntimeException("Failed to read config from repo", e); } } private static ConfigPropertyData read(final Repository repo, final RevCommit commit, final String path) throws IOException { ConfigPropertyData data = new ConfigPropertyData(); data.timestamp = new Date(1000L * commit.getCommitTime()); data.path = normalisePath(path); data.revision = commit.getId().getName(); data.properties = readProperties(repo, commit, path); return data; } private static List<ConfigPropertyValue> readProperties(final Repository repo, final RevCommit commit, final String path) throws IOException { // Read all properties Map<String, Map<String, ConfigPropertyValue>> config = parseCommit(repo, commit); // Now extract the properties from the path requested final Map<String, ConfigPropertyValue> properties = readProperties(config, path, true); return new ArrayList<>(properties.values()); } private static Map<String, ConfigPropertyValue> readProperties(final Map<String, Map<String, ConfigPropertyValue>> config, final String path, final boolean includeParents) { Map<String, ConfigPropertyValue> properties = new HashMap<>(); final List<String> paths = includeParents ? splitPath(path) : Collections.singletonList(path); for (String pathComponent : paths) { final Map<String, ConfigPropertyValue> pathComponentProperties = config.get(pathComponent); if (pathComponentProperties != null) { // First pick up hierarchy includes if (pathComponentProperties.containsKey(KEY_INCLUDE)) { for (String includePath : getIncludePaths(pathComponentProperties.get(KEY_INCLUDE))) properties.putAll(readProperties(config, includePath, true)); } // Next pick up single-path includes if (pathComponentProperties.containsKey(KEY_INCLUDE_SHALLOW)) { for (String includePath : getIncludePaths(pathComponentProperties.get(KEY_INCLUDE_SHALLOW))) properties.putAll(readProperties(config, includePath, true)); } // Now override with local properties properties.putAll(pathComponentProperties); } } return properties; } static String[] getIncludePaths(final ConfigPropertyValue includeonly) { return includeonly.value.split("\n"); } private static String normalisePath(String path) { // Remove double slashes path = path.replace(" if (path.startsWith("/")) // Remove leading slash if present path = path.substring(1); if (path.endsWith("/")) // Remove trailing slash if present path = path.substring(0, path.length() - 1); return path; } static List<String> splitPath(String path) { path = normalisePath(path); List<String> hierarchy = new ArrayList<>(); hierarchy.add(""); // root final String[] components = StringUtils.split(path, '/'); for (int i = 1; i <= components.length; i++) { hierarchy.add(StringUtils.join(components, '/', 0, i)); } return hierarchy; } public static void write(final Repository repo, final String name, final String email, final Map<String, Map<String, ConfigPropertyValue>> data, final ConfigChangeMode changeMode, final String message) { final File workTree = repo.getWorkTree(); if (changeMode == ConfigChangeMode.WIPE_ALL) { // Remove all existing config try { for (File file : workTree.listFiles()) { if (!StringUtils.startsWithIgnoreCase(file.getName(), ".git")) FileUtils.forceDelete(file); } } catch (IOException e) { throw new RuntimeException("Error clearing current work tree!", e); } } // Now write all config try { for (Map.Entry<String, Map<String, ConfigPropertyValue>> entry : data.entrySet()) { final String path = entry.getKey(); final Map<String, ConfigPropertyValue> props = entry.getValue(); final File folder = new File(workTree, path.replace('/', File.separatorChar)); // Make sure the path exists FileUtils.forceMkdir(folder); if (changeMode == ConfigChangeMode.WIPE_REFERENCED_PATHS) { File[] files = folder.listFiles((FileFilter) FileFilterUtils.fileFileFilter()); if (files != null) for (File file : files) FileUtils.forceDelete(file); } for (Map.Entry<String, ConfigPropertyValue> propEntry : props.entrySet()) { final File file = new File(folder, propEntry.getKey()); try { FileHelper.write(file, propEntry.getValue().value); } catch (IOException e) { throw new IOException("Error writing to " + file, e); } } } } catch (IOException e) { throw new RuntimeException("Error writing properties to work tree!", e); } // Commit the changes to the repository { try { Git git = new Git(repo); // Add all changes git.add().addFilepattern(".").call(); // Now commit git.commit().setAll(true).setAuthor(name, email).setMessage(message).call(); } catch (GitAPIException e) { throw new RuntimeException("Error committing changes!", e); } } } public static Map<String, Map<String, ConfigPropertyValue>> parseCommit(final Repository repo, final RevCommit commit) throws IOException { final String id = commit.getId().getName(); Map<String, Map<String, ConfigPropertyValue>> parsed; parsed = COMMIT_CACHE.getIfPresent(id); if (parsed == null) { parsed = _parseCommit(repo, commit); COMMIT_CACHE.put(id, parsed); } return parsed; } private static Map<String, Map<String, ConfigPropertyValue>> _parseCommit(final Repository repo, final RevCommit commit) throws IOException { TreeWalk walk = new TreeWalk(repo); walk.addTree(commit.getTree()); walk.setRecursive(false); // Map of Path to properties defined at this path Map<String, Map<String, ConfigPropertyValue>> all = new HashMap<>(); all.put("", new HashMap<>()); while (walk.next()) { if (walk.isSubtree()) { final String path = walk.getPathString(); all.put(path, new HashMap<>()); walk.enterSubtree(); } else { final String path; final String propertyName; { final String pathString = walk.getPathString(); final int lastSlash = pathString.lastIndexOf('/'); if (lastSlash == -1) { path = ""; propertyName = pathString; } else { path = pathString.substring(0, lastSlash); propertyName = pathString.substring(lastSlash + 1); } } final byte[] bytes = repo.open(walk.getObjectId(0)).getCachedBytes(); // Parse the data as a UTF-8 String final String str = new String(bytes, StandardCharsets.UTF_8); ConfigPropertyValue val = new ConfigPropertyValue(path, propertyName, str); all.get(path).put(propertyName, val); } } return all; } public static void reset(final Repository repo) { try { new Git(repo).reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD").call(); } catch (GitAPIException e) { throw new RuntimeException("Failed to issue git reset HEAD!", e); } } public static void addRemote(final Repository repo, final String remote, final String url) { try { // Add the new remote { final RemoteAddCommand remoteAdd = new Git(repo).remoteAdd(); remoteAdd.setName(remote); remoteAdd.setUri(new URIish(url)); remoteAdd.call(); } // Set up tracking { StoredConfig config = repo.getConfig(); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, "master", "remote", remote); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, "master", "merge", "refs/heads/master"); config.save(); } } catch (IOException | URISyntaxException | GitAPIException e) { throw new RuntimeException("Failed to issue git remote add", e); } } public static void pull(final Repository repo, final String remote, final CredentialsProvider credentials) { try { new Git(repo).pull().setRemote(remote).setStrategy(MergeStrategy.OURS).setCredentialsProvider(credentials).call(); } catch (GitAPIException e) { throw new RuntimeException("Failed to issue git pull", e); } } public static void push(final Repository repo, final String remote, final CredentialsProvider credentials) { try { new Git(repo).push().setForce(true).setRemote(remote).setCredentialsProvider(credentials).call(); } catch (GitAPIException e) { throw new RuntimeException("Failed to issue git pull", e); } } public static List<ConfigCommit> log(final Repository repo, final int max) { try { Git git = new Git(repo); final Iterable<RevCommit> commits = git.log().setMaxCount(max).call(); List<ConfigCommit> ret = new ArrayList<>(); for (RevCommit commit : commits) { final PersonIdent author = commit.getAuthorIdent(); final Date timestamp = new Date(commit.getCommitTime() * 1000L); ret.add(new ConfigCommit(timestamp, author.getName(), author.getEmailAddress(), commit.getFullMessage())); } return ret; } catch (GitAPIException e) { throw new RuntimeException("Error issuing git log", e); } } }
package eu.netide.core.caos.composition; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.Path; public class CompositionSpecificationLoader { public static CompositionSpecification Load(Path filePath) throws JAXBException, IOException { return Load(new String(Files.readAllBytes(filePath))); } public static CompositionSpecification Load(String xml) throws JAXBException { JAXBContext context = JAXBContext.newInstance(CompositionSpecification.class); Unmarshaller unmarshaller = context.createUnmarshaller(); //unmarshaller.setEventHandler(new DefaultValidationEventHandler()); // Use only for debugging - print validation erros to stdout return (CompositionSpecification) unmarshaller.unmarshal(new StringReader(xml)); } }
package org.epics.pvmanager.jca; import gov.aps.jca.CAException; import gov.aps.jca.Context; import gov.aps.jca.JCALibrary; import gov.aps.jca.Monitor; import java.util.logging.Level; import java.util.logging.Logger; import org.epics.pvmanager.ChannelHandler; import org.epics.pvmanager.DataSource; import org.epics.pvmanager.vtype.DataTypeSupport; import com.cosylab.epics.caj.CAJContext; import gov.aps.jca.jni.JNIContext; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.epics.pvmanager.util.Executors.namedPool; /** * A data source that uses jca. * <p> * Type support can be configured by passing a custom {@link JCATypeSupport} * to the constructor. * * @author carcassi */ public class JCADataSource extends DataSource { static { // Install type support for the types it generates. DataTypeSupport.install(); } private static final Logger log = Logger.getLogger(JCADataSource.class.getName()); private final Context ctxt; private final int monitorMask; private final boolean varArraySupported; private final boolean dbePropertySupported; private final JCATypeSupport typeSupport; private final boolean rtypValueOnly; private final boolean honorZeroPrecision; /** * Creates a new data source using pure Java implementation and all the * defaults described in {@link JCADataSourceBuilder}. */ public JCADataSource() { this(new JCADataSourceBuilder()); } /** * Creates a new data source using the given context. The context will * never be closed. * * @param jcaContext the context to be used * @param monitorMask Monitor.VALUE, ... * @deprecated use {@link JCADataSourceBuilder} */ @Deprecated public JCADataSource(Context jcaContext, int monitorMask) { this(new JCADataSourceBuilder().jcaContext(jcaContext).monitorMask(monitorMask)); } /** * Creates a new data source using the className to create the context. * * @param className JCALibrary.CHANNEL_ACCESS_JAVA, JCALibrary.JNI_THREAD_SAFE, ... * @param monitorMask Monitor.VALUE, ... * @deprecated use {@link JCADataSourceBuilder} */ @Deprecated public JCADataSource(String className, int monitorMask) { this(new JCADataSourceBuilder().jcaContextClass(className).monitorMask(monitorMask)); } /** * Creates a new data source using the given context. The context will * never be closed. The type mapping con be configured with a custom * type support. * * @param jcaContext the context to be used * @param monitorMask Monitor.VALUE, ... * @param typeSupport type support to be used * @deprecated use {@link JCADataSourceBuilder} */ @Deprecated public JCADataSource(Context jcaContext, int monitorMask, JCATypeSupport typeSupport) { this(new JCADataSourceBuilder().jcaContext(jcaContext).monitorMask(monitorMask) .typeSupport(typeSupport)); } /** * Creates a new data source using the given context. The context will * never be closed. The type mapping con be configured with a custom * type support. * * @param jcaContext the context to be used * @param monitorMask Monitor.VALUE, ... * @param typeSupport type support to be used * @param dbePropertySupported whether metadata monitors should be used * @param varArraySupported true if var array should be used * @deprecated use {@link JCADataSourceBuilder} */ @Deprecated public JCADataSource(Context jcaContext, int monitorMask, JCATypeSupport typeSupport, boolean dbePropertySupported, boolean varArraySupported) { this(new JCADataSourceBuilder().jcaContext(jcaContext).monitorMask(monitorMask) .typeSupport(typeSupport).dbePropertySupported(dbePropertySupported) .varArraySupported(varArraySupported)); } protected JCADataSource(JCADataSourceBuilder builder) { super(true); // Some properties are not pre-initialized to the default, // so if they were not set, we should initialize them. // Default JCA context is pure Java if (builder.jcaContext == null) { ctxt = JCADataSourceBuilder.createContext(JCALibrary.CHANNEL_ACCESS_JAVA); } else { ctxt = builder.jcaContext; } try { if (ctxt instanceof CAJContext) { ((CAJContext) ctxt).setDoNotShareChannels(true); } } catch (Throwable t) { log.log(Level.WARNING, "Couldn't change CAJContext to doNotShareChannels: this may cause some rare notification problems.", t); } // Default type support are the VTypes if (builder.typeSupport == null) { typeSupport = new JCATypeSupport(new JCAVTypeAdapterSet()); } else { typeSupport = builder.typeSupport; } // Default support for var array needs to be detected if (builder.varArraySupported == null) { varArraySupported = JCADataSourceBuilder.isVarArraySupported(ctxt); } else { varArraySupported = builder.varArraySupported; } monitorMask = builder.monitorMask; dbePropertySupported = builder.dbePropertySupported; rtypValueOnly = builder.rtypValueOnly; honorZeroPrecision = builder.honorZeroPrecision; if (useContextSwitchForAccessRightCallback()) { contextSwitch = Executors.newSingleThreadExecutor(namedPool("PVMgr JCA Workaround ")); } else { contextSwitch = null; } } @Override public void close() { super.close(); ctxt.dispose(); } /** * The context used by the data source. * * @return the data source context */ public Context getContext() { return ctxt; } /** * The monitor mask used for this data source. * * @return the monitor mask */ public int getMonitorMask() { return monitorMask; } /** * Whether the metadata monitor should be established. * * @return true if using metadata monitors */ public boolean isDbePropertySupported() { return dbePropertySupported; } @Override protected ChannelHandler createChannel(String channelName) { return new JCAChannelHandler(channelName, this); } JCATypeSupport getTypeSupport() { return typeSupport; } /** * True whether the context can use variable arrays (all * array monitor request will have an element count of 0). * * @return true if variable size arrays are supported */ public boolean isVarArraySupported() { return varArraySupported; } /** * True if should only ask value for RTYP fields. * * @return true if asking for value only */ public boolean isRtypValueOnly() { return rtypValueOnly; } /** * True if zero precision should be honored, or disregarded. * * @return true if zero precision setting is honored */ public boolean isHonorZeroPrecision() { return honorZeroPrecision; } /** * Determines whether the context supports variable arrays * or not. * * @param context a JCA Context * @return true if supports variable sized arrays */ @Deprecated public static boolean isVarArraySupported(Context context) { return JCADataSourceBuilder.isVarArraySupported(context); } final boolean useContextSwitchForAccessRightCallback() { if (ctxt instanceof JNIContext) { return true; } return false; } ExecutorService getContextSwitch() { return contextSwitch; } private final ExecutorService contextSwitch; }
package com.orientechnologies.orient.core.storage.impl.local; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.orientechnologies.common.concur.resource.OSharedResourceAdaptive; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.io.OIOException; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.config.OStorageClusterConfiguration; import com.orientechnologies.orient.core.config.OStorageClusterLocalLHPEOverflowConfiguration; import com.orientechnologies.orient.core.config.OStorageClusterLocalLHPEStatisticConfiguration; import com.orientechnologies.orient.core.config.OStorageFileConfiguration; import com.orientechnologies.orient.core.config.OStoragePhysicalClusterLHPEPSConfiguration; import com.orientechnologies.orient.core.exception.OStorageException; import com.orientechnologies.orient.core.memory.OMemoryWatchDog; import com.orientechnologies.orient.core.serialization.OMemoryInputStream; import com.orientechnologies.orient.core.serialization.OMemoryStream; import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OIntegerSerializer; import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLongSerializer; import com.orientechnologies.orient.core.storage.OCluster; import com.orientechnologies.orient.core.storage.OPhysicalPosition; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.storage.fs.OFile; /** * @author Andrey Lomakin * @since 26.07.12 */ public class OClusterLocalLHPEPS extends OSharedResourceAdaptive implements OCluster { public static final String TYPE = "PHYSICAL"; private static final String DEF_EXTENSION = ".ocl"; private static final int INITIAL_D = 10; private static final int DEF_SIZE = (1 << (INITIAL_D + 1)) * OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES; private static final int GROUP_COUNT = 2; private static final double storageSplitOverflow = 0.75; private static final double storageMergeOverflow = 0.5; private long lastOverflowBucket = -1; private long recordSplitPointer = 0; private long roundCapacity; private int g; private int d; private long pageSize; private long nextPageSize; private long size; private long mainBucketsSize; private BitSet splittedBuckets; private Map<Long, Integer> mainBucketOverflowInfoByIndex; private Map<Long, Integer> groupBucketOverflowInfoByIndex; private Map<Long, Integer>[] groupBucketOverflowInfoByChainLength; private int maxChainIndex; private OMultiFileSegment fileSegment; private int id; private OStoragePhysicalClusterLHPEPSConfiguration config; private String name; private OClusterLocalLHPEOverflow overflowSegment; private OClusterLocalLHPEStatistic overflowStatistic; private final ThreadLocal<Map<Long, OClusterLocalLHPEBucket>> mainBucketCache = new ThreadLocal<Map<Long, OClusterLocalLHPEBucket>>() { @Override protected Map<Long, OClusterLocalLHPEBucket> initialValue() { return new HashMap<Long, OClusterLocalLHPEBucket>( 32); } }; private final ThreadLocal<Map<Long, OClusterLocalLHPEBucket>> overflowBucketCache = new ThreadLocal<Map<Long, OClusterLocalLHPEBucket>>() { @Override protected Map<Long, OClusterLocalLHPEBucket> initialValue() { return new HashMap<Long, OClusterLocalLHPEBucket>( 32); } }; private final Set<OClusterLocalLHPEBucket> mainBucketsToStore = new HashSet<OClusterLocalLHPEBucket>(32); private final Set<OClusterLocalLHPEBucket> overflowBucketsToStore = new HashSet<OClusterLocalLHPEBucket>(32); private OStorageLocal storage; public OClusterLocalLHPEPS() { super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean()); initState(); } public void configure(OStorage iStorage, int iId, String iClusterName, String iLocation, int iDataSegmentId, Object... iParameters) throws IOException { storage = (OStorageLocal) iStorage; config = new OStoragePhysicalClusterLHPEPSConfiguration(iStorage.getConfiguration(), iId, iDataSegmentId); config.name = iClusterName; init(iStorage, iId, iClusterName, iDataSegmentId); } public void configure(OStorage iStorage, OStorageClusterConfiguration iConfig) throws IOException { config = (OStoragePhysicalClusterLHPEPSConfiguration) iConfig; storage = (OStorageLocal) iStorage; init(iStorage, config.getId(), config.getName(), config.getDataSegmentId()); } public void create(int iStartSize) throws IOException { acquireExclusiveLock(); try { if (iStartSize == -1) iStartSize = DEF_SIZE; if (config.root.clusters.size() <= config.id) config.root.clusters.add(config); else config.root.clusters.set(config.id, config); fileSegment.create(iStartSize); overflowSegment.create((iStartSize * 20) / 100); overflowStatistic.create(-1); fileSegment.allocateSpace((int) (mainBucketsSize * OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES)); } finally { releaseExclusiveLock(); } } public void open() throws IOException { acquireExclusiveLock(); try { fileSegment.open(); overflowSegment.open(); overflowStatistic.open(); deserializeState(); } finally { releaseExclusiveLock(); } } private void init(final OStorage iStorage, final int iId, final String iClusterName, final int iDataSegmentId) throws IOException { OFileUtils.checkValidName(iClusterName); OStorageLocal storage = (OStorageLocal) iStorage; config.setDataSegmentId(iDataSegmentId); config.id = iId; config.name = iClusterName; name = iClusterName; id = iId; if (fileSegment == null) { fileSegment = new OMultiFileSegment(storage, config, DEF_EXTENSION, OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES); config.setOverflowFile(new OStorageClusterLocalLHPEOverflowConfiguration(config, OStorageVariableParser.DB_PATH_VARIABLE + '/' + config.name, config.fileType, config.fileMaxSize)); config.setOverflowStatisticsFile(new OStorageClusterLocalLHPEStatisticConfiguration(config, OStorageVariableParser.DB_PATH_VARIABLE + '/' + config.name, config.fileType, config.fileMaxSize)); overflowSegment = new OClusterLocalLHPEOverflow(storage, config.getOverflowFile(), this); overflowStatistic = new OClusterLocalLHPEStatistic(storage, config.getOverflowStatisticsFile()); } } public void close() throws IOException { acquireExclusiveLock(); try { serializeState(); fileSegment.close(); overflowSegment.close(); overflowStatistic.close(); } finally { releaseExclusiveLock(); } } public void delete() throws IOException { acquireExclusiveLock(); try { truncate(); for (OFile f : fileSegment.files) f.delete(); fileSegment.files = null; overflowSegment.delete(); overflowStatistic.delete(); } finally { releaseExclusiveLock(); } } public void set(ATTRIBUTES iAttribute, Object iValue) throws IOException { if (iAttribute == null) throw new IllegalArgumentException("attribute is null"); final String stringValue = iValue != null ? iValue.toString() : null; acquireExclusiveLock(); try { switch (iAttribute) { case NAME: setNameInternal(stringValue); break; case DATASEGMENT: setDataSegmentInternal(stringValue); break; } } finally { releaseExclusiveLock(); } } private void setNameInternal(final String iNewName) { if (storage.getClusterIdByName(iNewName) > -1) throw new IllegalArgumentException("Cluster with name '" + iNewName + "' already exists"); for (int i = 0; i < fileSegment.files.length; i++) { final String osFileName = fileSegment.files[i].getName(); if (osFileName.startsWith(name)) { final File newFile = new File(storage.getStoragePath() + '/' + iNewName + osFileName.substring(osFileName.lastIndexOf(name) + name.length())); for (OStorageFileConfiguration conf : config.infoFiles) { if (conf.parent.name.equals(name)) conf.parent.name = iNewName; if (conf.path.endsWith(osFileName)) conf.path = conf.path.replace(osFileName, newFile.getName()); } boolean renamed = fileSegment.files[i].renameTo(newFile); while (!renamed) { OMemoryWatchDog.freeMemory(100); renamed = fileSegment.files[i].renameTo(newFile); } } } config.name = iNewName; overflowSegment.rename(name, iNewName); overflowStatistic.rename(name, iNewName); storage.renameCluster(name, iNewName); name = iNewName; storage.getConfiguration().update(); } /** * Assigns a different data-segment id. * * @param iName * Data-segment's name */ private void setDataSegmentInternal(final String iName) { final int dataId = storage.getDataSegmentIdByName(iName); config.setDataSegmentId(dataId); storage.getConfiguration().update(); } private void initState() { lastOverflowBucket = -1; recordSplitPointer = 0; g = GROUP_COUNT; d = INITIAL_D; pageSize = 1 << d; nextPageSize = pageSize << 1; roundCapacity = pageSize; size = nextPageSize; mainBucketsSize = size; splittedBuckets = new BitSet((int) pageSize); mainBucketOverflowInfoByIndex = new HashMap<Long, Integer>(1024); groupBucketOverflowInfoByIndex = new HashMap<Long, Integer>(1024); groupBucketOverflowInfoByChainLength = new HashMap[16]; maxChainIndex = 0; } public void truncate() throws IOException { acquireExclusiveLock(); try { long localSize = size; long position = 0; while (localSize > 0) { OClusterLocalLHPEBucket bucket = loadMainBucket(position); while (true) { for (int n = 0; n < bucket.getSize(); n++) { OPhysicalPosition ppos = new OPhysicalPosition(); ppos = getPhysicalPosition(ppos); if (storage.checkForRecordValidity(ppos)) storage.getDataSegmentById(ppos.dataSegmentId).deleteRecord(ppos.dataSegmentPos); localSize } if (bucket.getOverflowBucket() < 0) break; bucket = loadOverflowBucket(bucket.getOverflowBucket()); } position++; } fileSegment.truncate(); overflowSegment.truncate(); overflowStatistic.truncate(); initState(); } finally { releaseExclusiveLock(); } } public int getDataSegmentId() { acquireSharedLock(); try { return config.getDataSegmentId(); } finally { releaseSharedLock(); } } public boolean addPhysicalPosition(OPhysicalPosition iPPosition) throws IOException { acquireExclusiveLock(); try { long[] pos = calculatePageIndex(iPPosition.clusterPosition); long position = pos[0]; final long offset = pos[1]; final int prevChainLength = getMainBucketOverflowChainLength(position); int chainLength = 0; OClusterLocalLHPEBucket currentBucket = loadMainBucket(position); while (true) { for (int i = 0; i < currentBucket.getSize(); i++) { long bucketKey = currentBucket.getKey(i); if (bucketKey == iPPosition.clusterPosition) return false; } if (currentBucket.getOverflowBucket() > -1) { currentBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); chainLength++; } else break; } if (currentBucket.getSize() < OClusterLocalLHPEBucket.BUCKET_CAPACITY) currentBucket.addPhysicalPosition(iPPosition); else { final OverflowBucketInfo bucketInfo = popOverflowBucket(); final OClusterLocalLHPEBucket overflowBucket = bucketInfo.bucket; currentBucket.setOverflowBucket(bucketInfo.index); overflowBucket.addPhysicalPosition(iPPosition); chainLength++; updateMainBucketOverflowChainLength(position, chainLength); updateBucketGroupOverflowChainLength(offset, chainLength - prevChainLength); } size++; splitBucketIfNeeded(); storeBuckets(); return true; } finally { clearCache(); releaseExclusiveLock(); } } public OPhysicalPosition getPhysicalPosition(OPhysicalPosition iPPosition) throws IOException { acquireSharedLock(); try { final BucketInfo bucketInfo = findBucket(iPPosition.clusterPosition); if (bucketInfo == null) return null; return bucketInfo.bucket.getPhysicalPosition(bucketInfo.index); } finally { clearCache(); releaseSharedLock(); } } public void updateDataSegmentPosition(long iPosition, int iDataSegmentId, long iDataPosition) throws IOException { acquireExclusiveLock(); try { final BucketInfo bucketInfo = findBucket(iPosition); if (!bucketInfo.bucket.isOverflowBucket()) { final int idOffset = OClusterLocalLHPEBucket.getDataSegmentIdOffset(bucketInfo.index); final long filePos = bucketInfo.bucket.getFilePosition() + idOffset; final long[] pos = fileSegment.getRelativePosition(filePos); final OFile file = fileSegment.files[(int) pos[0]]; long p = pos[1]; final byte[] serializedDataSegment = OClusterLocalLHPEBucket.serializeDataSegmentId(iDataSegmentId); final byte[] serializedDataPosition = OClusterLocalLHPEBucket.serializeDataPosition(iDataPosition); file.write(p, serializedDataSegment); file.write(p + serializedDataSegment.length, serializedDataPosition); } else overflowSegment.updateDataSegmentPosition(bucketInfo.bucket, bucketInfo.index, iDataSegmentId, iDataPosition); } finally { clearCache(); releaseExclusiveLock(); } } public void removePhysicalPosition(long iPosition) throws IOException { acquireExclusiveLock(); try { final long[] pos = calculatePageIndex(iPosition); long position = pos[0]; final long offset = pos[1]; OClusterLocalLHPEBucket mainBucket = loadMainBucket(position); OClusterLocalLHPEBucket currentBucket = mainBucket; while (true) { for (int i = 0; i < currentBucket.getSize(); i++) { long bucketKey = currentBucket.getKey(i); if (bucketKey == iPosition) { currentBucket.removePhysicalPosition(i); size mergeBucketsIfNeeded(); compressChain(mainBucket, position, offset); } } if (currentBucket.getOverflowBucket() > -1) currentBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); else break; } storeBuckets(); } finally { clearCache(); releaseExclusiveLock(); } } public void updateRecordType(long iPosition, byte iRecordType) throws IOException { acquireExclusiveLock(); try { final BucketInfo bucketInfo = findBucket(iPosition); if (!bucketInfo.bucket.isOverflowBucket()) { final int recordTypeOffset = OClusterLocalLHPEBucket.getRecordTypeOffset(bucketInfo.index); final long filePos = bucketInfo.bucket.getFilePosition() + recordTypeOffset; final long[] pos = fileSegment.getRelativePosition(filePos); final OFile file = fileSegment.files[(int) pos[0]]; long p = pos[1]; file.writeByte(p, iRecordType); } else overflowSegment.updateRecordType(bucketInfo.bucket, bucketInfo.index, iRecordType); } finally { clearCache(); releaseExclusiveLock(); } } public void updateVersion(long iPosition, int iVersion) throws IOException { acquireExclusiveLock(); try { final BucketInfo bucketInfo = findBucket(iPosition); if (!bucketInfo.bucket.isOverflowBucket()) { final int versionOffset = OClusterLocalLHPEBucket.getVersionOffset(bucketInfo.index); final byte[] serializedVersion = OClusterLocalLHPEBucket.serializeVersion(iVersion); final long filePos = bucketInfo.bucket.getFilePosition() + versionOffset; final long[] pos = fileSegment.getRelativePosition(filePos); final OFile file = fileSegment.files[(int) pos[0]]; long p = pos[1]; file.write(p, serializedVersion); } else overflowSegment.updateVersion(bucketInfo.bucket, bucketInfo.index, iVersion); } finally { clearCache(); releaseExclusiveLock(); } } public long getEntries() { return size; } public long getFirstEntryPosition() { return 0; } public long getLastEntryPosition() { return 0; } public void lock() { acquireSharedLock(); } public void unlock() { releaseSharedLock(); } public String getType() { return TYPE; } public int getId() { return id; } public void synch() throws IOException { acquireSharedLock(); try { serializeState(); fileSegment.synch(); overflowSegment.synch(); overflowStatistic.synch(); } finally { releaseSharedLock(); } } public void setSoftlyClosed(boolean softlyClosed) throws IOException { acquireExclusiveLock(); try { fileSegment.setSoftlyClosed(softlyClosed); overflowSegment.setSoftlyClosed(softlyClosed); overflowStatistic.setSoftlyClosed(softlyClosed); } finally { releaseExclusiveLock(); } } public String getName() { return name; } public boolean generatePositionBeforeCreation() { return true; } public long getRecordsSize() { acquireSharedLock(); try { long calculatedSize = fileSegment.getFilledUpTo(); long localSize = size; long position = 0; while (localSize > 0) { OClusterLocalLHPEBucket bucket = loadMainBucket(position); while (true) { for (int n = 0; n < bucket.getSize(); n++) { OPhysicalPosition ppos = bucket.getPhysicalPosition(n); if (ppos.dataSegmentPos > -1 && ppos.recordVersion > -1) calculatedSize += storage.getDataSegmentById(ppos.dataSegmentId).getRecordSize(ppos.dataSegmentPos); localSize } if (bucket.getOverflowBucket() < 0) break; bucket = loadOverflowBucket(bucket.getOverflowBucket()); } position++; } return calculatedSize; } catch (IOException e) { throw new OIOException("Error on calculating cluster size for: " + name, e); } finally { releaseSharedLock(); } } public Iterator<Long> absoluteIterator() { return null; // TODO } private long calcPositionToMerge() { return mainBucketsSize - pageSize * g - 1; } private void mergeBucketsIfNeeded() throws IOException { double currentCapacity = 1.0 * size / (mainBucketsSize * OClusterLocalLHPEBucket.BUCKET_CAPACITY); if (currentCapacity < storageMergeOverflow) mergeBuckets(); } private void mergeBuckets() throws IOException { long positionToMerge = calcPositionToMerge(); if (positionToMerge < 0) { g if (g < GROUP_COUNT) { g = 2 * GROUP_COUNT - 1; nextPageSize = pageSize; pageSize = pageSize >>> 1; roundCapacity = pageSize; splittedBuckets = new BitSet((int) pageSize); } splittedBuckets.set(0, (int) pageSize); recordSplitPointer = roundCapacity; rebuildGroupOverflowChain(); positionToMerge = calcPositionToMerge(); } splittedBuckets.clear((int) positionToMerge); Map<Long, OClusterLocalLHPEBucket> bucketMap = new HashMap<Long, OClusterLocalLHPEBucket>(g); List<Long> bucketsToMerge = new ArrayList<Long>(g); for (long ptr = positionToMerge; ptr <= positionToMerge + pageSize * g; ptr += pageSize) { final OClusterLocalLHPEBucket bucket = loadMainBucket(ptr); bucketMap.put(ptr, bucket); bucketsToMerge.add(ptr); } for (long currentBucketPosition : bucketsToMerge) { OClusterLocalLHPEBucket currentBucket = bucketMap.get(currentBucketPosition); while (true) { for (int i = 0; i < currentBucket.getSize();) { long bucketKey = currentBucket.getKey(i); long position = calculatePageIndex(bucketKey)[0]; OClusterLocalLHPEBucket bucketToAdd = bucketMap.get(position); if (currentBucketPosition != position) { while (bucketToAdd.getSize() >= OClusterLocalLHPEBucket.BUCKET_CAPACITY && bucketToAdd.getOverflowBucket() > -1) bucketToAdd = loadOverflowBucket(bucketToAdd.getOverflowBucket()); if (bucketToAdd.getSize() >= OClusterLocalLHPEBucket.BUCKET_CAPACITY) { OverflowBucketInfo overflowBucket = popOverflowBucket(); bucketToAdd.setOverflowBucket(overflowBucket.index); bucketToAdd = overflowBucket.bucket; } bucketToAdd.addPhysicalPosition(currentBucket.getPhysicalPosition(i)); currentBucket.removePhysicalPosition(i); } else i++; } if (currentBucket.getOverflowBucket() > -1) currentBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); else break; } } for (long currentBucketPosition : bucketsToMerge) { final OClusterLocalLHPEBucket currentBucket = bucketMap.get(currentBucketPosition); compressChain(currentBucket, currentBucketPosition, positionToMerge); } recordSplitPointer = splittedBuckets.nextClearBit(0); } private void clearCache() { mainBucketCache.get().clear(); overflowBucketCache.get().clear(); } private OClusterLocalLHPEBucket loadMainBucket(long position) throws IOException { final Map<Long, OClusterLocalLHPEBucket> bucketCache = mainBucketCache.get(); OClusterLocalLHPEBucket clusterBucket = bucketCache.get(position); if (clusterBucket != null) return clusterBucket; final long filePos = position * OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES; final long[] pos = fileSegment.getRelativePosition(filePos); final OFile file = fileSegment.files[(int) pos[0]]; long p = pos[1]; final byte[] buffer = new byte[OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES]; file.read(p, buffer, OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES); clusterBucket = new OClusterLocalLHPEBucket(buffer, this, filePos, false); bucketCache.put(position, clusterBucket); return clusterBucket; } private OClusterLocalLHPEBucket loadOverflowBucket(long position) throws IOException { final Map<Long, OClusterLocalLHPEBucket> bucketCache = overflowBucketCache.get(); OClusterLocalLHPEBucket clusterBucket = bucketCache.get(position); if (clusterBucket != null) return clusterBucket; final long filePos = position * OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES; clusterBucket = overflowSegment.loadBucket(filePos); bucketCache.put(position, clusterBucket); return clusterBucket; } private void storeBuckets() throws IOException { for (OClusterLocalLHPEBucket mainBucket : mainBucketsToStore) { final long filledUpTo = fileSegment.getFilledUpTo(); final long endPos = mainBucket.getFilePosition() + OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES; if (endPos > filledUpTo) fileSegment.allocateSpace((int) (endPos - filledUpTo)); mainBucket.serialize(); final long filePos = mainBucket.getFilePosition(); final long[] pos = fileSegment.getRelativePosition(filePos); final OFile file = fileSegment.files[(int) pos[0]]; long p = pos[1]; file.write(p, mainBucket.getBuffer()); } mainBucketsToStore.clear(); for (OClusterLocalLHPEBucket overflowBucket : overflowBucketsToStore) { overflowBucket.serialize(); overflowSegment.updateBucket(overflowBucket); } overflowBucketsToStore.clear(); } private void splitBucketIfNeeded() throws IOException { double currentCapacity = 1.0 * size / (mainBucketsSize * OClusterLocalLHPEBucket.BUCKET_CAPACITY); if (currentCapacity > storageSplitOverflow) splitBuckets(); } private void splitBuckets() throws IOException { final long positionToSplit = calcPositionToSplit(); splittedBuckets.set((int) positionToSplit); final long positionToAdd = positionToSplit + pageSize * g; if (mainBucketsSize - 1 < positionToAdd) { final long requiredSpace = (positionToAdd + 1) * OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES; if (requiredSpace > fileSegment.getFilledUpTo()) fileSegment.allocateSpace((int) (requiredSpace - fileSegment.getFilledUpTo())); mainBucketsSize = positionToAdd + 1; } OClusterLocalLHPEBucket addedBucket = loadMainBucket(positionToAdd); Map<Long, OClusterLocalLHPEBucket> bucketMap = new HashMap<Long, OClusterLocalLHPEBucket>(g); List<Long> bucketsToSplit = new ArrayList<Long>(g); for (long ptr = positionToSplit; ptr < positionToSplit + pageSize * g; ptr += pageSize) { final OClusterLocalLHPEBucket bucket = loadMainBucket(ptr); bucketMap.put(ptr, bucket); bucketsToSplit.add(ptr); } bucketMap.put(positionToAdd, addedBucket); int chainLength = 0; int prevChainLength = getMainBucketOverflowChainLength(positionToAdd); for (long currentBucketPosition : bucketsToSplit) { OClusterLocalLHPEBucket currentBucket = bucketMap.get(currentBucketPosition); while (true) { for (int i = 0; i < currentBucket.getSize();) { long bucketKey = currentBucket.getKey(i); long position = calculatePageIndex(bucketKey)[0]; OClusterLocalLHPEBucket bucketToAdd = bucketMap.get(position); if (currentBucketPosition != position) { while (bucketToAdd.getSize() >= OClusterLocalLHPEBucket.BUCKET_CAPACITY && bucketToAdd.getOverflowBucket() > -1) bucketToAdd = loadOverflowBucket(bucketToAdd.getOverflowBucket()); if (bucketToAdd.getSize() >= OClusterLocalLHPEBucket.BUCKET_CAPACITY) { OverflowBucketInfo bucketInfo = popOverflowBucket(); bucketToAdd.setOverflowBucket(bucketInfo.index); bucketToAdd = bucketInfo.bucket; if (position == positionToAdd) chainLength++; } bucketToAdd.addPhysicalPosition(currentBucket.getPhysicalPosition(i)); currentBucket.removePhysicalPosition(i); } else i++; } if (currentBucket.getOverflowBucket() > -1) currentBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); else break; } } updateMainBucketOverflowChainLength(positionToAdd, chainLength); updateBucketGroupOverflowChainLength(positionToSplit, chainLength - prevChainLength); for (long currentBucketPosition : bucketsToSplit) { final OClusterLocalLHPEBucket currentBucket = bucketMap.get(currentBucketPosition); compressChain(currentBucket, currentBucketPosition, positionToSplit); } recordSplitPointer = splittedBuckets.nextClearBit((int) recordSplitPointer); if (recordSplitPointer == roundCapacity) { recordSplitPointer = 0; splittedBuckets.clear(); g++; if (g == 2 * GROUP_COUNT) { roundCapacity = nextPageSize; pageSize = nextPageSize; nextPageSize <<= 1; g = GROUP_COUNT; splittedBuckets = new BitSet((int) pageSize); } rebuildGroupOverflowChain(); } } private BucketInfo findBucket(long clusterPosition) throws IOException { long position = calculatePageIndex(clusterPosition)[0]; OClusterLocalLHPEBucket currentBucket = loadMainBucket(position); while (true) { for (int i = 0; i < currentBucket.getSize(); i++) { long bucketKey = currentBucket.getKey(i); if (bucketKey == clusterPosition) { final BucketInfo bucketInfo = new BucketInfo(); bucketInfo.index = i; bucketInfo.bucket = currentBucket; return bucketInfo; } } if (currentBucket.getOverflowBucket() > -1) currentBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); else return null; } } private void compressChain(OClusterLocalLHPEBucket mainBucket, long index, long offset) throws IOException { OClusterLocalLHPEBucket currentBucket = mainBucket; while (true) { if (currentBucket.getOverflowBucket() < 0) break; int diff = OClusterLocalLHPEBucket.BUCKET_CAPACITY - currentBucket.getSize(); OClusterLocalLHPEBucket nextBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); while (nextBucket.getSize() == 0) { if (nextBucket.getOverflowBucket() > -1) nextBucket = loadOverflowBucket(nextBucket.getOverflowBucket()); else break; } if (nextBucket.getSize() > 0) for (int i = 0; i < diff; i++) { final OPhysicalPosition physicalPosition = nextBucket.getPhysicalPosition(nextBucket.getSize() - 1); currentBucket.addPhysicalPosition(physicalPosition); nextBucket.removePhysicalPosition(nextBucket.getSize() - 1); while (nextBucket.getSize() == 0) { if (nextBucket.getOverflowBucket() > -1) nextBucket = loadOverflowBucket(nextBucket.getOverflowBucket()); else break; } if (nextBucket.getSize() == 0) break; } if (currentBucket.getSize() < OClusterLocalLHPEBucket.BUCKET_CAPACITY) { break; } if (currentBucket.getOverflowBucket() > -1) currentBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); else { break; } } int chainLength = 0; final int prevChainLength = getMainBucketOverflowChainLength(index); currentBucket = mainBucket; while (true) { if (currentBucket.getOverflowBucket() < 0) break; final OClusterLocalLHPEBucket nextBucket = loadOverflowBucket(currentBucket.getOverflowBucket()); if (nextBucket.getSize() == 0) { putBucketToOverflowList(nextBucket, currentBucket.getOverflowBucket()); currentBucket.setOverflowBucket(-1); break; } chainLength++; currentBucket = nextBucket; } updateMainBucketOverflowChainLength(index, chainLength); updateBucketGroupOverflowChainLength(offset, chainLength - prevChainLength); if (index == mainBucketsSize - 1 && mainBucket.getSize() == 0 && chainLength == 0) { mainBucketsSize mainBucketsToStore.remove(mainBucket); final byte[] empty = new byte[OClusterLocalLHPEBucket.BUCKET_SIZE_IN_BYTES]; final long filePos = mainBucket.getFilePosition(); final long[] pos = fileSegment.getRelativePosition(filePos); final OFile file = fileSegment.files[(int) pos[0]]; long p = pos[1]; file.write(p, empty); } } private void putBucketToOverflowList(OClusterLocalLHPEBucket bucket, long index) throws IOException { OClusterLocalLHPEBucket currentBucket = bucket; while (true) { long nextBucket = currentBucket.getOverflowBucket(); currentBucket.setOverflowBucket(lastOverflowBucket); lastOverflowBucket = index; if (nextBucket == -1) break; currentBucket = loadOverflowBucket(nextBucket); index = nextBucket; } } private OverflowBucketInfo popOverflowBucket() throws IOException { OverflowBucketInfo result = new OverflowBucketInfo(); if (lastOverflowBucket > -1) { result.bucket = loadOverflowBucket(lastOverflowBucket); result.index = lastOverflowBucket; lastOverflowBucket = result.bucket.getOverflowBucket(); result.bucket.setOverflowBucket(-1); } else { OClusterLocalLHPEBucket bucket = overflowSegment.createBucket(); result.index = overflowSegment.getBucketsSize() - 1; result.bucket = bucket; overflowBucketCache.get().put(result.index, bucket); } return result; } void addToMainStoreList(final OClusterLocalLHPEBucket bucket) { mainBucketsToStore.add(bucket); } void addToOverflowStoreList(final OClusterLocalLHPEBucket bucket) { overflowBucketsToStore.add(bucket); } private long[] calculatePageIndex(long key) { long[] result = new long[2]; long ps = pageSize; long offset = calculateOffset(key, ps); long group; if (!splittedBuckets.get((int) offset)) group = calculateGroup(key, g); else if (g != 2 * GROUP_COUNT - 1) group = calculateGroup(key, g + 1); else { ps = nextPageSize; offset = calculateOffset(key, ps); group = calculateGroup(key, GROUP_COUNT); } result[0] = ps * group + offset; result[1] = offset; return result; } private long calcPositionToSplit() { if (maxChainIndex < 1) return recordSplitPointer; else { for (int i = maxChainIndex; i >= 1; i final Map<Long, Integer> infoMap = groupBucketOverflowInfoByChainLength[i]; if (infoMap == null || infoMap.isEmpty()) continue; for (Long index : infoMap.keySet()) { if (!splittedBuckets.get(index.intValue())) { return index; } } } } return recordSplitPointer; } private int getMainBucketOverflowChainLength(long bucketIndex) { final Integer mainBucketOverflowInfo = mainBucketOverflowInfoByIndex.get(bucketIndex); if (mainBucketOverflowInfo == null) return 0; return mainBucketOverflowInfo; } private void updateBucketGroupOverflowChainLength(long groupIndex, int diff) { if (diff == 0) return; Integer mainBucketOverflowInfo = groupBucketOverflowInfoByIndex.get(groupIndex); int prevChainLength = 0; if (mainBucketOverflowInfo == null) { mainBucketOverflowInfo = diff; groupBucketOverflowInfoByIndex.put(groupIndex, mainBucketOverflowInfo); } else { prevChainLength = mainBucketOverflowInfo; mainBucketOverflowInfo += diff; if (mainBucketOverflowInfo == 0) groupBucketOverflowInfoByIndex.remove(groupIndex); else groupBucketOverflowInfoByIndex.put(groupIndex, mainBucketOverflowInfo); } Map<Long, Integer> prevChainMap = null; if (prevChainLength > 0) prevChainMap = groupBucketOverflowInfoByChainLength[prevChainLength]; if (mainBucketOverflowInfo > 0) { if (mainBucketOverflowInfo == groupBucketOverflowInfoByChainLength.length) { final Map<Long, Integer>[] newGroupBucketOverflow = new HashMap[groupBucketOverflowInfoByChainLength.length << 1]; System.arraycopy(groupBucketOverflowInfoByChainLength, 0, newGroupBucketOverflow, 0, groupBucketOverflowInfoByChainLength.length); groupBucketOverflowInfoByChainLength = newGroupBucketOverflow; } Map<Long, Integer> nextChainMap = groupBucketOverflowInfoByChainLength[mainBucketOverflowInfo]; if (nextChainMap == null) { nextChainMap = new HashMap<Long, Integer>(1024); groupBucketOverflowInfoByChainLength[mainBucketOverflowInfo] = nextChainMap; } nextChainMap.put(groupIndex, mainBucketOverflowInfo); } if (mainBucketOverflowInfo > maxChainIndex) maxChainIndex = mainBucketOverflowInfo; if (prevChainMap != null) prevChainMap.remove(groupIndex); if (prevChainLength == maxChainIndex) { while (maxChainIndex >= 0 && (groupBucketOverflowInfoByChainLength[maxChainIndex] == null || groupBucketOverflowInfoByChainLength[maxChainIndex] .isEmpty())) maxChainIndex } } private void updateMainBucketOverflowChainLength(long mainBucketIndex, int val) { Integer mainBucketOverflowInfo = mainBucketOverflowInfoByIndex.get(mainBucketIndex); if (mainBucketOverflowInfo == null) { if (val == 0) return; mainBucketOverflowInfoByIndex.put(mainBucketIndex, val); } else { if (mainBucketOverflowInfo == val) return; if (val == 0) mainBucketOverflowInfoByIndex.remove(mainBucketIndex); else mainBucketOverflowInfoByIndex.put(mainBucketIndex, val); } } private void rebuildGroupOverflowChain() { groupBucketOverflowInfoByChainLength = new HashMap[16]; groupBucketOverflowInfoByIndex.clear(); maxChainIndex = -1; for (long i = 0; i < pageSize; i++) { int chainLength = 0; for (int cg = 0; cg < g; cg++) { final Integer mainBucketOverflowInfo = mainBucketOverflowInfoByIndex.get(cg * pageSize + i); if (mainBucketOverflowInfo != null) chainLength += mainBucketOverflowInfo; } if (chainLength > 0) { if (chainLength > groupBucketOverflowInfoByChainLength.length) { final Map<Long, Integer>[] newGroupBucketOverflow = new HashMap[groupBucketOverflowInfoByChainLength.length << 1]; System.arraycopy(groupBucketOverflowInfoByChainLength, 0, newGroupBucketOverflow, 0, groupBucketOverflowInfoByChainLength.length); groupBucketOverflowInfoByChainLength = newGroupBucketOverflow; } Map<Long, Integer> infoMap = groupBucketOverflowInfoByChainLength[chainLength]; if (infoMap == null) { infoMap = new HashMap<Long, Integer>(1024); groupBucketOverflowInfoByChainLength[chainLength] = infoMap; } infoMap.put(i, chainLength); groupBucketOverflowInfoByIndex.put(i, chainLength); if (chainLength > maxChainIndex) maxChainIndex = chainLength; } } } private static long calculateGroup(long key, int gValue) { if (gValue == 2) return key & 1; if (gValue == 3) return key % 3; throw new IllegalStateException("Invalid group value, should be 2 or 3 but is " + gValue); } private static long calculateOffset(long key, long pageSize) { return key & (pageSize - 1); } private void serializeState() throws IOException { final OFile file = fileSegment.files[0]; int pos = 0; file.writeHeaderLong(0, lastOverflowBucket); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, recordSplitPointer); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, roundCapacity); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, g); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, d); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, pageSize); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, nextPageSize); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, size); pos += OLongSerializer.LONG_SIZE; file.writeHeaderLong(pos, mainBucketsSize); OMemoryStream byteArrayOutputStream = new OMemoryStream(splittedBuckets.size() / 8); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(splittedBuckets); objectOutputStream.flush(); objectOutputStream.close(); byte[] serializedBitSet = byteArrayOutputStream.toByteArray(); objectOutputStream = null; byteArrayOutputStream = null; final int statisticSize = (OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE) * mainBucketOverflowInfoByIndex.size() + serializedBitSet.length + 2 * OIntegerSerializer.INT_SIZE; overflowStatistic.truncate(); final OFile statisticsFile = overflowStatistic.file; statisticsFile.allocateSpace(statisticSize); pos = 0; statisticsFile.writeInt(pos, serializedBitSet.length); pos += OIntegerSerializer.INT_SIZE; statisticsFile.write(pos, serializedBitSet); pos += serializedBitSet.length; serializedBitSet = null; statisticsFile.writeInt(pos, mainBucketOverflowInfoByIndex.size()); for (Map.Entry<Long, Integer> statisticEntry : mainBucketOverflowInfoByIndex.entrySet()) { statisticsFile.writeLong(pos, statisticEntry.getKey()); pos += OLongSerializer.LONG_SIZE; statisticsFile.writeInt(pos, statisticEntry.getValue()); pos += OIntegerSerializer.INT_SIZE; } } private void deserializeState() throws IOException { final OFile file = fileSegment.files[0]; int pos = 0; lastOverflowBucket = file.readHeaderLong(0); pos += OLongSerializer.LONG_SIZE; recordSplitPointer = file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; roundCapacity = file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; g = (int) file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; d = (int) file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; pageSize = file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; nextPageSize = (int) file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; size = file.readHeaderLong(pos); pos += OLongSerializer.LONG_SIZE; mainBucketsSize = file.readHeaderLong(pos); final OFile statisticsFile = overflowStatistic.file; pos = 0; final int serializedBitSetSize = statisticsFile.readInt(pos); pos += OIntegerSerializer.INT_SIZE; byte[] serializedBitSet = new byte[serializedBitSetSize]; statisticsFile.read(pos, serializedBitSet, serializedBitSetSize); OMemoryInputStream byteArrayInputStream = new OMemoryInputStream(serializedBitSet); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); try { splittedBuckets = (BitSet) objectInputStream.readObject(); } catch (ClassNotFoundException e) { throw new OStorageException("Error during opening cluster " + name, e); } finally { objectInputStream.close(); byteArrayInputStream.close(); } pos += serializedBitSet.length; objectInputStream.close(); objectInputStream = null; byteArrayInputStream = null; serializedBitSet = null; final int mapSize = statisticsFile.readInt(pos); pos += OIntegerSerializer.INT_SIZE; mainBucketOverflowInfoByIndex = new HashMap<Long, Integer>(mapSize); for (int i = 0; i < mapSize; i++) { final long key = statisticsFile.readLong(pos); pos += OLongSerializer.LONG_SIZE; final int value = statisticsFile.readInt(pos); pos += OIntegerSerializer.INT_SIZE; mainBucketOverflowInfoByIndex.put(key, value); } rebuildGroupOverflowChain(); } private static final class BucketInfo { private OClusterLocalLHPEBucket bucket; int index; } private static final class OverflowBucketInfo { private OClusterLocalLHPEBucket bucket; long index; } }
package io.debezium.connector.postgresql; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Path; import java.sql.SQLException; import java.util.Collection; import java.util.Map; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.kafka.connect.runtime.standalone.StandaloneConfig; import org.apache.kafka.connect.storage.FileOffsetBackingStore; import org.apache.kafka.connect.util.Callback; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.debezium.doc.FixFor; import io.debezium.document.Document; import io.debezium.document.DocumentReader; import io.debezium.engine.ChangeEvent; import io.debezium.engine.DebeziumEngine; import io.debezium.engine.DebeziumEngine.CompletionCallback; import io.debezium.engine.format.Avro; import io.debezium.engine.format.CloudEvents; import io.debezium.engine.format.Json; import io.debezium.junit.EqualityCheck; import io.debezium.junit.SkipTestRule; import io.debezium.junit.SkipWhenKafkaVersion; import io.debezium.junit.SkipWhenKafkaVersion.KafkaVersion; import io.debezium.util.LoggingContext; import io.debezium.util.Testing; /** * Integration tests for Debezium Engine API * * @author Jiri Pechanec */ public class DebeziumEngineIT { private static final Logger LOGGER = LoggerFactory.getLogger(DebeziumEngineIT.class); protected static final Path OFFSET_STORE_PATH = Testing.Files.createTestingPath("connector-offsets.txt").toAbsolutePath(); @Rule public SkipTestRule skipTest = new SkipTestRule(); @Before public void before() throws SQLException { OFFSET_STORE_PATH.getParent().toFile().mkdirs(); OFFSET_STORE_PATH.toFile().delete(); TestHelper.dropDefaultReplicationSlot(); TestHelper.dropAllSchemas(); TestHelper.execute( "CREATE SCHEMA engine;", "CREATE TABLE engine.test (id INT PRIMARY KEY, val VARCHAR(32));", "INSERT INTO engine.test VALUES(1, 'value1');"); } @Test @FixFor("DBZ-1807") public void shouldSerializeToJson() throws Exception { final Properties props = new Properties(); props.putAll(TestHelper.defaultConfig().build().asMap()); props.setProperty("name", "debezium-engine"); props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector"); props.setProperty(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG, OFFSET_STORE_PATH.toAbsolutePath().toString()); props.setProperty("offset.flush.interval.ms", "0"); props.setProperty("converter.schemas.enable", "false"); CountDownLatch allLatch = new CountDownLatch(1); final ExecutorService executor = Executors.newFixedThreadPool(1); try (final DebeziumEngine<ChangeEvent<String, String>> engine = DebeziumEngine.create(Json.class).using(props) .notifying((records, committer) -> { for (ChangeEvent<String, String> r : records) { Assertions.assertThat(r.key()).isNotNull(); Assertions.assertThat(r.value()).isNotNull(); try { final Document key = DocumentReader.defaultReader().read(r.key()); final Document value = DocumentReader.defaultReader().read(r.value()); Assertions.assertThat(key.getInteger("id")).isEqualTo(1); Assertions.assertThat(value.getDocument("after").getInteger("id")).isEqualTo(1); Assertions.assertThat(value.getDocument("after").getString("val")).isEqualTo("value1"); } catch (IOException e) { throw new IllegalStateException(e); } allLatch.countDown(); committer.markProcessed(r); } committer.markBatchFinished(); }).using(this.getClass().getClassLoader()).build()) { executor.execute(() -> { LoggingContext.forConnector(getClass().getSimpleName(), "debezium-engine", "engine"); engine.run(); }); allLatch.await(5000, TimeUnit.MILLISECONDS); assertThat(allLatch.getCount()).isEqualTo(0); } } @Test @FixFor("DBZ-1807") @SkipWhenKafkaVersion(check = EqualityCheck.EQUAL, value = KafkaVersion.KAFKA_1XX, description = "Not compatible with Kafka 1.x") public void shouldSerializeToAvro() throws Exception { final Properties props = new Properties(); props.putAll(TestHelper.defaultConfig().build().asMap()); props.setProperty("name", "debezium-engine"); props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector"); props.setProperty(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG, OFFSET_STORE_PATH.toAbsolutePath().toString()); props.setProperty("offset.flush.interval.ms", "0"); props.setProperty("converter.schema.registry.url", "http://localhost:" + TestHelper.defaultJdbcConfig().getPort()); CountDownLatch allLatch = new CountDownLatch(1); final ExecutorService executor = Executors.newFixedThreadPool(1); try (final DebeziumEngine<ChangeEvent<byte[], byte[]>> engine = DebeziumEngine.create(Avro.class).using(props) .notifying((records, committer) -> { Assert.fail("Should not be invoked due to serialization error"); }) .using(new CompletionCallback() { @Override public void handle(boolean success, String message, Throwable error) { Assertions.assertThat(success).isFalse(); Assertions.assertThat(message).contains("Failed to serialize Avro data from topic test_server.engine.test"); allLatch.countDown(); } }) .build()) { executor.execute(() -> { LoggingContext.forConnector(getClass().getSimpleName(), "debezium-engine", "engine"); engine.run(); }); allLatch.await(5000, TimeUnit.MILLISECONDS); assertThat(allLatch.getCount()).isEqualTo(0); } } @Test @FixFor("DBZ-1807") public void shouldSerializeToCloudEvents() throws Exception { final Properties props = new Properties(); props.putAll(TestHelper.defaultConfig().build().asMap()); props.setProperty("name", "debezium-engine"); props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector"); props.setProperty(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG, OFFSET_STORE_PATH.toAbsolutePath().toString()); props.setProperty("offset.flush.interval.ms", "0"); props.setProperty("converter.schemas.enable", "false"); CountDownLatch allLatch = new CountDownLatch(1); final ExecutorService executor = Executors.newFixedThreadPool(1); try (final DebeziumEngine<ChangeEvent<String, String>> engine = DebeziumEngine.create(Json.class, CloudEvents.class).using(props) .notifying((records, committer) -> { for (ChangeEvent<String, String> r : records) { try { final Document key = DocumentReader.defaultReader().read(r.key()); Assertions.assertThat(key.getInteger("id")).isEqualTo(1); Assertions.assertThat(r.value()).isNotNull(); final Document value = DocumentReader.defaultReader().read(r.value()); Assertions.assertThat(value.getString("id")).contains("txId"); Assertions.assertThat(value.getDocument("data").getDocument("payload").getDocument("after").getInteger("id")).isEqualTo(1); Assertions.assertThat(value.getDocument("data").getDocument("payload").getDocument("after").getString("val")).isEqualTo("value1"); } catch (IOException e) { throw new IllegalStateException(e); } allLatch.countDown(); committer.markProcessed(r); } committer.markBatchFinished(); }).using(this.getClass().getClassLoader()).build()) { executor.execute(() -> { LoggingContext.forConnector(getClass().getSimpleName(), "debezium-engine", "engine"); engine.run(); }); allLatch.await(5000, TimeUnit.MILLISECONDS); assertThat(allLatch.getCount()).isEqualTo(0); } } private static final AtomicInteger offsetStoreSetCalls = new AtomicInteger(); public static class TestOffsetStore extends FileOffsetBackingStore { @Override public Future<Map<ByteBuffer, ByteBuffer>> get(Collection<ByteBuffer> keys) { LOGGER.info("Get offsets called"); return super.get(keys); } @Override public Future<Void> set(Map<ByteBuffer, ByteBuffer> values, Callback<Void> callback) { LOGGER.info("Set offsets called"); offsetStoreSetCalls.incrementAndGet(); return super.set(values, callback); } } @Test @FixFor("DBZ-2461") public void testOffsetsCommitAfterStop() throws Exception { final AtomicReference<Throwable> exception = new AtomicReference<>(); DebeziumEngine<ChangeEvent<String, String>> engine; TestHelper.execute("DROP TABLE IF EXISTS tests;", "CREATE TABLE tests (id SERIAL PRIMARY KEY);"); final Properties props = new Properties(); props.putAll(TestHelper.defaultConfig().build().asMap()); props.setProperty("name", "debezium-engine"); props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector"); props.setProperty(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG, OFFSET_STORE_PATH.toAbsolutePath().toString()); props.setProperty("offset.flush.interval.ms", "3000"); props.setProperty("converter.schemas.enable", "false"); props.setProperty("slot.drop.on.stop", "false"); props.setProperty("offset.storage", TestOffsetStore.class.getName()); engine = DebeziumEngine.create(Json.class).using(props).using(new DebeziumEngine.ConnectorCallback() { @Override public void connectorStarted() { } @Override public void connectorStopped() { } }).using((success, message, error) -> { exception.compareAndSet(null, error); }).notifying((records, committer) -> { try { for (ChangeEvent<String, String> record : records) { committer.markProcessed(record); } committer.markBatchFinished(); } catch (Exception e) { Testing.printError(e); } }).build(); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(engine); while (offsetStoreSetCalls.get() < 1) { TestHelper.execute("INSERT INTO tests VALUES(default)"); } engine.close(); Assertions.assertThat(offsetStoreSetCalls.get()).isGreaterThanOrEqualTo(1); offsetStoreSetCalls.set(0); for (int i = 0; i < 100; i++) { TestHelper.execute("INSERT INTO tests VALUES(default)"); } executor.execute(engine); while (offsetStoreSetCalls.get() < 1) { TestHelper.execute("INSERT INTO tests VALUES(default)"); } engine.close(); Assertions.assertThat(offsetStoreSetCalls.get()).isGreaterThanOrEqualTo(1); Assertions.assertThat(exception.get()).isNull(); } }
//$HeadURL$ package org.deegree.record.persistence.genericrecordstore; import static org.deegree.protocol.csw.CSWConstants.APISO_NS; import static org.deegree.protocol.csw.CSWConstants.APISO_PREFIX; import static org.deegree.protocol.csw.CSWConstants.CSW_202_NS; import static org.deegree.protocol.csw.CSWConstants.CSW_202_RECORD; import static org.deegree.protocol.csw.CSWConstants.CSW_PREFIX; import static org.deegree.protocol.csw.CSWConstants.DC_LOCAL_PART; import static org.deegree.protocol.csw.CSWConstants.DC_NS; import static org.deegree.protocol.csw.CSWConstants.GMD_LOCAL_PART; import static org.deegree.protocol.csw.CSWConstants.GMD_NS; import static org.deegree.protocol.csw.CSWConstants.GMD_PREFIX; import static org.slf4j.LoggerFactory.getLogger; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.deegree.commons.jdbc.ConnectionManager; import org.deegree.commons.utils.Pair; import org.deegree.commons.utils.kvp.InvalidParameterValueException; import org.deegree.commons.utils.time.DateUtils; import org.deegree.commons.xml.XMLAdapter; import org.deegree.filter.FilterEvaluationException; import org.deegree.filter.OperatorFilter; import org.deegree.filter.expression.Literal; import org.deegree.filter.sql.expression.SQLLiteral; import org.deegree.filter.sql.postgis.PostGISWhereBuilder; import org.deegree.filter.sql.postgis.PropertyNameMapping; import org.deegree.protocol.csw.CSWConstants; import org.deegree.protocol.csw.CSWConstants.ResultType; import org.deegree.protocol.csw.CSWConstants.SetOfReturnableElements; import org.deegree.record.persistence.RecordStore; import org.deegree.record.persistence.RecordStoreException; import org.deegree.record.persistence.RecordStoreOptions; import org.deegree.record.persistence.genericrecordstore.parsing.ISOQPParsing; import org.deegree.record.persistence.iso19115.jaxb.ISORecordStoreConfig; import org.deegree.record.publication.DeleteTransaction; import org.deegree.record.publication.InsertTransaction; import org.deegree.record.publication.RecordProperty; import org.deegree.record.publication.TransactionOperation; import org.deegree.record.publication.UpdateTransaction; import org.slf4j.Logger; public class ISORecordStore implements RecordStore { private static final Logger LOG = getLogger( ISORecordStore.class ); /** * registers the typeNames that are applicable to this recordStore and maps a typeName to a format, if it is DC or * ISO */ private static Map<QName, Integer> typeNames = new HashMap<QName, Integer>(); private final String connectionId; // if true, use old-style for spatial predicates (intersects instead of ST_Intersecs) private boolean useLegacyPredicates; /** * shows the encoding of the database that is used */ private String encoding; private final boolean inspire; private final boolean generateFileIds; /** * maps the specific returnable element format to a concrete table in the backend<br> * brief, summary, full */ private static final Map<SetOfReturnableElements, String> formatTypeInISORecordStore = new HashMap<SetOfReturnableElements, String>(); static { formatTypeInISORecordStore.put( SetOfReturnableElements.brief, "recordbrief" ); formatTypeInISORecordStore.put( SetOfReturnableElements.summary, "recordsummary" ); formatTypeInISORecordStore.put( SetOfReturnableElements.full, "recordfull" ); // typeNames.put( new QName( "", "", "" ), 1 ); typeNames.put( new QName( CSW_202_NS, DC_LOCAL_PART, "" ), 1 ); typeNames.put( new QName( CSW_202_NS, DC_LOCAL_PART, CSW_PREFIX ), 1 ); typeNames.put( new QName( DC_NS, "", "dc" ), 1 ); typeNames.put( new QName( GMD_NS, GMD_LOCAL_PART, "" ), 2 ); typeNames.put( new QName( GMD_NS, GMD_LOCAL_PART, GMD_PREFIX ), 2 ); typeNames.put( new QName( APISO_NS, "", APISO_PREFIX ), 2 ); } /** * Creates a new {@link ISORecordStore} instance from the given JAXB configuration object. * * @param config */ public ISORecordStore( ISORecordStoreConfig config ) { this.connectionId = config.getConnId(); inspire = config.isRequireInspireCompliance() == null ? false : config.isRequireInspireCompliance(); generateFileIds = config.isGenerateFileIdentifiers() == null ? false : config.isGenerateFileIdentifiers(); } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#describeRecord(javax.xml.stream.XMLStreamWriter) */ @Override public void describeRecord( XMLStreamWriter writer, QName typeName ) { try { BufferedInputStream bais; URLConnection urlConn = null; /* * if typeName is csw:Record */ if ( typeName.equals( new QName( CSW_202_NS, DC_LOCAL_PART, CSW_PREFIX ) ) ) { urlConn = new URL( CSW_202_RECORD ).openConnection(); } /* * if typeName is gmd:MD_Metadata */ else if ( typeName.equals( new QName( GMD_NS, GMD_LOCAL_PART, GMD_PREFIX ) ) ) { urlConn = new URL( "http: writer.writeAttribute( "parentSchema", "http: } /* * if the typeName is no registered in this recordprofile */ else { String errorMessage = "The typeName " + typeName + "is not supported by this profile. "; LOG.debug( errorMessage ); throw new IllegalArgumentException( errorMessage ); } urlConn.setDoInput( true ); bais = new BufferedInputStream( urlConn.getInputStream() ); Charset charset = encoding == null ? Charset.defaultCharset() : Charset.forName( encoding ); InputStreamReader isr = new InputStreamReader( bais, charset ); readXMLFragment( isr, writer ); } catch ( MalformedURLException e ) { LOG.debug( "error: " + e.getMessage(), e ); } catch ( IOException e ) { LOG.debug( "error: " + e.getMessage(), e ); } catch ( Exception e ) { LOG.debug( "error: " + e.getMessage(), e ); } } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#destroy() */ @Override public void destroy() { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#init() */ @Override public void init() throws RecordStoreException { LOG.debug( "init" ); // lockManager = new DefaultLockManager( this, "LOCK_DB" ); Connection conn = null; try { Class.forName( "org.postgresql.Driver" ); conn = ConnectionManager.getConnection( connectionId ); encoding = determinePostGRESEncoding( conn ); String version = determinePostGISVersion( conn ); if ( version.startsWith( "0." ) || version.startsWith( "1.0" ) || version.startsWith( "1.1" ) || version.startsWith( "1.2" ) ) { LOG.debug( "PostGIS version is " + version + " -- using legacy (pre-SQL-MM) predicates." ); useLegacyPredicates = true; } else { LOG.debug( "PostGIS version is " + version + " -- using modern (SQL-MM) predicates." ); } } catch ( SQLException e ) { e.printStackTrace(); } catch ( ClassNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @param conn * @return the encoding of the PostGRES database. */ private String determinePostGRESEncoding( Connection conn ) { String encodingPostGRES = "UTF-8"; Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery( "SHOW server_encoding" ); rs.next(); encodingPostGRES = rs.getString( 1 ); LOG.debug( "PostGRES encoding: " + encodingPostGRES ); stmt.close(); rs.close(); } catch ( Exception e ) { LOG.warn( "Could not determine PostGRES encoding: " + e.getMessage() + " -- defaulting to UTF-8" ); closeSafely( null, stmt, rs ); } return encodingPostGRES; } private String determinePostGISVersion( Connection conn ) { String version = "1.0"; Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery( "SELECT postgis_version()" ); rs.next(); String postGISVersion = rs.getString( 1 ); version = postGISVersion.split( " " )[0]; LOG.debug( "PostGIS version: " + version ); stmt.close(); rs.close(); } catch ( Exception e ) { LOG.warn( "Could not determine PostGIS version: " + e.getMessage() + " -- defaulting to 1.0.0" ); closeSafely( null, stmt, rs ); } return version; } private void closeSafely( Connection conn, Statement stmt, ResultSet rs ) { if ( rs != null ) { try { rs.close(); } catch ( SQLException e ) { LOG.warn( e.getMessage(), e ); } } if ( stmt != null ) { try { stmt.close(); } catch ( SQLException e ) { LOG.warn( e.getMessage(), e ); } } if ( conn != null ) { try { conn.close(); } catch ( SQLException e ) { LOG.warn( e.getMessage(), e ); } } } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#getTypeNames() */ @Override public Map<QName, Integer> getTypeNames() { return typeNames; } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#getRecords(javax.xml.stream.XMLStreamWriter, * javax.xml.namespace.QName) */ @Override public void getRecords( XMLStreamWriter writer, QName typeName, URI outputSchema, RecordStoreOptions recordStoreOptions ) throws SQLException, XMLStreamException, IOException { PostGISMappingsISODC mapping = new PostGISMappingsISODC(); PostGISWhereBuilder builder = null; // TODO sortProperty try { builder = new PostGISWhereBuilder( mapping, (OperatorFilter) recordStoreOptions.getFilter(), null, useLegacyPredicates ); } catch ( FilterEvaluationException e ) { e.printStackTrace(); } int profileFormatNumberOutputSchema = 0; int typeNameFormatNumber = 0; if ( typeNames.containsKey( typeName ) ) { typeNameFormatNumber = typeNames.get( typeName ); } if ( !typeName.getNamespaceURI().equals( outputSchema.toString() ) ) { for ( QName qName : typeNames.keySet() ) { if ( qName.getNamespaceURI().equals( outputSchema.toString() ) ) { profileFormatNumberOutputSchema = typeNames.get( qName ); } } } switch ( recordStoreOptions.getResultType() ) { case results: doResultsOnGetRecord( writer, typeName, profileFormatNumberOutputSchema, recordStoreOptions, builder ); break; case hits: doHitsOnGetRecord( writer, typeNameFormatNumber, profileFormatNumberOutputSchema, recordStoreOptions, formatTypeInISORecordStore.get( recordStoreOptions.getSetOfReturnableElements() ), ResultType.hits, builder ); break; case validate: // TODO } } /** * The mandatory "resultType" attribute in the GetRecords operation is set to "hits". * * @param writer * - the XMLStreamWriter * @param typeName * - the requested typeName * @param profileFormatNumberOutputSchema * - the format number of the outputSchema * @param propertyAttributes * - the properties that are identified by the request * @param con * - the JDBCConnection * @throws SQLException * @throws XMLStreamException * @throws IOException */ private void doHitsOnGetRecord( XMLStreamWriter writer, int typeNameFormatNumber, int profileFormatNumberOutputSchema, RecordStoreOptions recordStoreOptions, String formatType, ResultType resultType, PostGISWhereBuilder builder ) throws SQLException, XMLStreamException, IOException { int countRows = 0; int nextRecord = 0; int returnedRecords = 0; Connection conn = ConnectionManager.getConnection( connectionId ); StringBuilder s = generateSELECTStatement( formatType, recordStoreOptions, typeNameFormatNumber, profileFormatNumberOutputSchema, true, builder );// combinePreparedStatement( PreparedStatement ps = conn.prepareStatement( s.toString() ); /* * the parameter identified in the WHERE-builder replaces the "?" in the statement */ if ( builder != null && builder.getPropNameMappingList().size() > 0 ) { int i = 0; for ( SQLLiteral arg : builder.getWhereClause().getLiterals() ) { i++; LOG.debug( "Setting argument: " + arg ); ps.setObject( i, arg.getValue() ); } } ResultSet rs = ps.executeQuery(); while ( rs.next() ) { countRows = rs.getInt( 1 ); LOG.debug( "rs for rowCount: " + rs.getInt( 1 ) ); } if ( resultType.equals( ResultType.hits ) ) { writer.writeAttribute( "elementSet", recordStoreOptions.getSetOfReturnableElements().name() ); // writer.writeAttribute( "recordSchema", ""); writer.writeAttribute( "numberOfRecordsMatched", Integer.toString( countRows ) ); writer.writeAttribute( "numberOfRecordsReturned", Integer.toString( 0 ) ); writer.writeAttribute( "nextRecord", Integer.toString( 1 ) ); writer.writeAttribute( "expires", DateUtils.formatISO8601Date( new Date() ) ); } else { if ( countRows > recordStoreOptions.getMaxRecords() ) { nextRecord = recordStoreOptions.getMaxRecords() + 1; returnedRecords = recordStoreOptions.getMaxRecords(); } else { nextRecord = 0; returnedRecords = countRows - recordStoreOptions.getStartPosition() + 1; } writer.writeAttribute( "elementSet", recordStoreOptions.getSetOfReturnableElements().name() ); // writer.writeAttribute( "recordSchema", ""); writer.writeAttribute( "numberOfRecordsMatched", Integer.toString( countRows ) ); writer.writeAttribute( "numberOfRecordsReturned", Integer.toString( returnedRecords ) ); writer.writeAttribute( "nextRecord", Integer.toString( nextRecord ) ); writer.writeAttribute( "expires", DateUtils.formatISO8601Date( new Date() ) ); } ps.close(); rs.close(); conn.close(); } /** * Replace the dbTablenames with aliasNames. * * @param aliasCount * @param builder * @param whereClause * @param aliasMapping */ private void createWhereClauseWithAlias( int aliasCount, PostGISWhereBuilder builder, StringBuilder whereClause, Set<Pair<String, String>> aliasMapping ) { for ( PropertyNameMapping propName : builder.getPropNameMappingList() ) { if ( !propName.getTable().equals( PostGISMappingsISODC.DatabaseTables.datasets.name() ) ) { aliasMapping.add( new Pair<String, String>( propName.getTable(), propName.getTable() + Integer.toString( aliasCount ) ) ); aliasCount++; } } StringBuilder replaceWhereClause = new StringBuilder(); replaceWhereClause.append( builder.getWhereClause().getSQL() ); for ( Pair<String, String> alias : aliasMapping ) { Pattern p = Pattern.compile( alias.first + "[.]" ); Matcher m = p.matcher( (CharSequence) replaceWhereClause ); String replaceString = m.replaceFirst( alias.second + "." ); System.out.println( replaceString ); replaceWhereClause.delete( 0, replaceWhereClause.capacity() ); replaceWhereClause.append( replaceString ); } whereClause.append( replaceWhereClause ); } /** * The mandatory "resultType" attribute in the GetRecords operation is set to "results". * * @param writer * - the XMLStreamWriter * @param typeName * - the requested typeName * @param profileFormatNumberOutputSchema * - the format number of the outputSchema * @param recordStoreOptions * - the properties that are identified by the request * @param con * - the JDBCConnection * @throws SQLException * @throws XMLStreamException * @throws IOException */ private void doResultsOnGetRecord( XMLStreamWriter writer, QName typeName, int profileFormatNumberOutputSchema, RecordStoreOptions recordStoreOptions, PostGISWhereBuilder builder ) throws SQLException, XMLStreamException, IOException { int typeNameFormatNumber = 0; if ( typeNames.containsKey( typeName ) ) { typeNameFormatNumber = typeNames.get( typeName ); } Connection conn = ConnectionManager.getConnection( connectionId ); ResultSet rs = null; PreparedStatement preparedStatement = null; switch ( recordStoreOptions.getSetOfReturnableElements() ) { case brief: StringBuilder selectBrief = generateSELECTStatement( formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.brief ), recordStoreOptions, typeNameFormatNumber, profileFormatNumberOutputSchema, false, builder ); preparedStatement = conn.prepareStatement( selectBrief.toString() ); doHitsOnGetRecord( writer, typeNameFormatNumber, profileFormatNumberOutputSchema, recordStoreOptions, formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.brief ), ResultType.results, builder ); break; case summary: StringBuilder selectSummary = generateSELECTStatement( formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.summary ), recordStoreOptions, typeNameFormatNumber, profileFormatNumberOutputSchema, false, builder ); preparedStatement = conn.prepareStatement( selectSummary.toString() ); doHitsOnGetRecord( writer, typeNameFormatNumber, profileFormatNumberOutputSchema, recordStoreOptions, formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.summary ), ResultType.results, builder ); break; case full: StringBuilder selectFull = generateSELECTStatement( formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.full ), recordStoreOptions, typeNameFormatNumber, profileFormatNumberOutputSchema, false, builder ); preparedStatement = conn.prepareStatement( selectFull.toString() ); doHitsOnGetRecord( writer, typeNameFormatNumber, profileFormatNumberOutputSchema, recordStoreOptions, formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.full ), ResultType.results, builder ); break; } /* * the parameter identified in the WHERE-builder replaces the "?" in the statement */ if ( builder != null && builder.getPropNameMappingList().size() > 0 ) { int i = 0; for ( SQLLiteral arg : builder.getWhereClause().getLiterals() ) { i++; LOG.debug( "Setting argument: " + arg ); preparedStatement.setObject( i, arg.getValue() ); } } rs = preparedStatement.executeQuery(); if ( rs != null && recordStoreOptions.getMaxRecords() != 0 ) { writeResultSet( rs, writer ); rs.close(); } conn.close(); } /** * Selectstatement for the constrainted tables. * * @param formatType * - brief, summary or full * @param recordStoreOptions * - properties that were requested * @param typeNameFormatNumber * - the format number that is identified by the requested typeName * @param profileFormatNumberOutputSchema * - the format number that is identified by the requested output schema * @param setCount * - if the COUNT method should be in the statement * @param builder * - the SQLWhereBuilder * @return * @throws IOException * @throws SQLException */ private StringBuilder generateSELECTStatement( String formatType, RecordStoreOptions recordStoreOptions, int typeNameFormatNumber, int profileFormatNumberOutputSchema, boolean setCount, PostGISWhereBuilder builder ) throws IOException, SQLException { int aliasCount = 0; StringBuilder whereClause = new StringBuilder(); Set<Pair<String, String>> aliasMapping = new HashSet<Pair<String, String>>(); createWhereClauseWithAlias( aliasCount, builder, whereClause, aliasMapping ); String fk_datasets = PostGISMappingsISODC.CommonColumnNames.fk_datasets.name(); String format = PostGISMappingsISODC.CommonColumnNames.format.name(); String data = PostGISMappingsISODC.CommonColumnNames.data.name(); String id = PostGISMappingsISODC.CommonColumnNames.id.name(); String datasets = PostGISMappingsISODC.DatabaseTables.datasets.name(); StringBuilder getDatasetIDs = new StringBuilder( 300 ); String formatTypeAlias = formatType + aliasCount; // String datasetsAlias = PostGISMappingsISODC.DatabaseTables.datasets.name() + Integer.toString( 1 ); StringBuilder COUNT_PRE; StringBuilder COUNT_SUF; StringBuilder SET_OFFSET; LOG.debug( "wherebuilder: " + builder ); getDatasetIDs.append( "SELECT " ).append( datasets ).append( '.' ); getDatasetIDs.append( id ); getDatasetIDs.append( " FROM " ).append( datasets ); // LEFT OUTER JOINs Iterator aliasIter = aliasMapping.iterator(); while ( aliasIter.hasNext() ) { Pair<String, String> aliasPair = (Pair<String, String>) aliasIter.next(); getDatasetIDs.append( " LEFT OUTER JOIN " ).append( aliasPair.first ); getDatasetIDs.append( " AS " ).append( aliasPair.second ).append( " ON " ); getDatasetIDs.append( aliasPair.second ).append( '.' ); getDatasetIDs.append( fk_datasets ).append( '=' ); getDatasetIDs.append( datasets ).append( '.' ).append( id ); } if ( whereClause != null ) { getDatasetIDs.append( " WHERE " ).append( whereClause ); } /* * precondition if there is a counting of rows needed */ if ( setCount == true ) { COUNT_PRE = new StringBuilder().append( "COUNT(" ); COUNT_SUF = new StringBuilder().append( ')' ); SET_OFFSET = new StringBuilder(); } else { COUNT_PRE = new StringBuilder(); COUNT_SUF = new StringBuilder(); SET_OFFSET = new StringBuilder(); if ( recordStoreOptions != null ) { SET_OFFSET.append( " OFFSET " ).append( Integer.toString( recordStoreOptions.getStartPosition() - 1 ) ); SET_OFFSET.append( " LIMIT " ).append( recordStoreOptions.getMaxRecords() ); } } // building the StringBuilder to get the BLOB data from backend StringBuilder s = new StringBuilder(); s.append( "SELECT " ).append( COUNT_PRE ).append( formatTypeAlias ).append( '.' ); s.append( data ).append( COUNT_SUF ); s.append( " FROM " ).append( formatType ).append( " AS " ).append( formatTypeAlias ); s.append( " WHERE " ).append( formatTypeAlias ).append( '.' ); s.append( fk_datasets ).append( " IN (" ); s.append( getDatasetIDs ).append( ')' ); s.append( " AND " ).append( formatTypeAlias ).append( '.' ); s.append( format ).append( '=' ); s.append( typeNameFormatNumber ).append( ' ' ).append( SET_OFFSET ).append( ";" ); LOG.info( s.toString() ); return s; } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#transaction(javax.xml.stream.XMLStreamWriter, * org.deegree.commons.configuration.JDBCConnections, java.util.List) */ @Override public List<Integer> transaction( XMLStreamWriter writer, TransactionOperation operations ) throws SQLException, XMLStreamException { List<Integer> affectedIds = new ArrayList<Integer>(); Connection conn = ConnectionManager.getConnection( connectionId ); PostGISMappingsISODC mapping = new PostGISMappingsISODC(); switch ( operations.getType() ) { case INSERT: InsertTransaction ins = (InsertTransaction) operations; for ( OMElement element : ins.getElement() ) { QName localName = element.getQName(); try { ExecuteStatements executeStatements = new ExecuteStatements(); if ( localName.equals( new QName( CSW_202_NS, "Record", CSW_PREFIX ) ) || localName.equals( new QName( CSW_202_NS, "Record", "" ) ) ) { executeStatements.executeInsertStatement( true, conn, affectedIds, new ISOQPParsing().parseAPDC( element ) ); } else { executeStatements.executeInsertStatement( false, conn, affectedIds, new ISOQPParsing().parseAPISO( element, inspire, conn ) ); } } catch ( IOException e ) { LOG.debug( "error: " + e.getMessage(), e ); } } break; /* * There is a known BUG here. If you update one complete record, there is no problem. If you update just some * properties, multiple properties like "keywords" are not correctly updated. Have a look at {@link * #recursiveElementKnotUpdate} */ case UPDATE: UpdateTransaction upd = (UpdateTransaction) operations; /** * if there should a complete record be updated or some properties */ if ( upd.getElement() != null ) { try { QName localName = upd.getElement().getQName(); ExecuteStatements executeStatements = new ExecuteStatements(); if ( localName.equals( new QName( CSW_202_NS, "Record", CSW_PREFIX ) ) || localName.equals( new QName( CSW_202_NS, "Record", "" ) ) ) { executeStatements.executeUpdateStatement( conn, affectedIds, new ISOQPParsing().parseAPDC( upd.getElement() ) ); } else { executeStatements.executeUpdateStatement( conn, affectedIds, new ISOQPParsing().parseAPISO( upd.getElement(), inspire, conn ) ); } } catch ( IOException e ) { LOG.debug( "error: " + e.getMessage(), e ); } } else { try { RecordStoreOptions gdds = new RecordStoreOptions( upd.getConstraint(), ResultType.results, SetOfReturnableElements.full ); int formatNumber = 0; Set<QName> qNameSet = new HashSet<QName>(); // TODO sortProperty PostGISWhereBuilder builder = new PostGISWhereBuilder( mapping, (OperatorFilter) upd.getConstraint(), null, useLegacyPredicates ); for ( QName propName : mapping.getPropToTableAndCol().keySet() ) { String nsURI = propName.getNamespaceURI(); String prefix = propName.getPrefix(); QName analysedQName = new QName( nsURI, "", prefix ); qNameSet.add( analysedQName ); } // if ( qNameSet.size() > 1 ) { // String message = // "There are different kinds of RecordStores affected by the request! Please decide on just one of the requested ones: "; // int i = 0; // for ( QName qNameError : qNameSet ) { // message += i + ". " + qNameError.toString() + " "; for ( QName qName : typeNames.keySet() ) { if ( qName.equals( qNameSet.iterator().next() ) ) { formatNumber = typeNames.get( qName ); } } PreparedStatement str = getRequestedIDStatement( formatTypeInISORecordStore.get( SetOfReturnableElements.full ), gdds, formatNumber, builder, conn ); ResultSet rsUpdatableDatasets = str.executeQuery(); List<Integer> updatableDatasets = new ArrayList<Integer>(); while ( rsUpdatableDatasets.next() ) { updatableDatasets.add( rsUpdatableDatasets.getInt( 1 ) ); } str.close(); rsUpdatableDatasets.close(); if ( updatableDatasets.size() != 0 ) { PreparedStatement stmt = null; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "SELECT " ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.full ) ); stringBuilder.append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.data.name() ); stringBuilder.append( " FROM " ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.full ) ); stringBuilder.append( " WHERE " ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.full ) ); stringBuilder.append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.format.name() ); stringBuilder.append( " = 2 AND " ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.full ) ); stringBuilder.append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ).append( " = ?;" ); for ( int i : updatableDatasets ) { stmt = conn.prepareStatement( stringBuilder.toString() ); stmt.setObject( 1, i ); ResultSet rsGetStoredFullRecordXML = stmt.executeQuery(); while ( rsGetStoredFullRecordXML.next() ) { for ( RecordProperty recProp : upd.getRecordProperty() ) { PropertyNameMapping propMapping = mapping.getMapping( recProp.getPropertyName() ); Object obje = mapping.getPostGISValue( (Literal<?>) recProp.getReplacementValue(), recProp.getPropertyName() ); // creating an OMElement read from backend byteData InputStream in = rsGetStoredFullRecordXML.getBinaryStream( 1 ); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader( in ); OMElement elementBuiltFromDB = new StAXOMBuilder( reader ).getDocument().getOMDocumentElement(); OMElement omElement = recursiveElementKnotUpdate( elementBuiltFromDB, elementBuiltFromDB.getChildElements(), propMapping.getColumn(), obje.toString() ); try { QName localName = omElement.getQName(); ExecuteStatements executeStatements = new ExecuteStatements(); if ( localName.equals( new QName( CSW_202_NS, "Record", CSW_PREFIX ) ) || localName.equals( new QName( CSW_202_NS, "Record", "" ) ) ) { executeStatements.executeUpdateStatement( conn, affectedIds, new ISOQPParsing().parseAPDC( omElement ) ); } else { executeStatements.executeUpdateStatement( conn, affectedIds, new ISOQPParsing().parseAPISO( omElement, inspire, conn ) ); } } catch ( IOException e ) { LOG.debug( "error: " + e.getMessage(), e ); } } } stmt.close(); rsGetStoredFullRecordXML.close(); } } } catch ( IOException e ) { LOG.debug( "error: " + e.getMessage(), e ); } catch ( FilterEvaluationException e ) { e.printStackTrace(); } catch ( NullPointerException e ) { e.printStackTrace(); } } break; case DELETE: DeleteTransaction delete = (DeleteTransaction) operations; PostGISWhereBuilder builder = null; int formatNumber = 0; int[] formatNumbers = null; PreparedStatement stmt = null; // if there is a typeName denoted, the record with this profile should be deleted. // if there is no typeName attribute denoted, every record matched should be deleted. if ( delete.getTypeName() != null ) { for ( QName qName : typeNames.keySet() ) { if ( qName.equals( delete.getTypeName() ) ) { formatNumber = typeNames.get( qName ); } } } else { formatNumbers = new int[2]; formatNumbers[0] = 1; formatNumbers[1] = 2; } if ( formatNumber == 0 ) { for ( int formatNum : formatNumbers ) { // TODO sortProperty try { builder = new PostGISWhereBuilder( mapping, (OperatorFilter) delete.getConstraint(), null, useLegacyPredicates ); } catch ( FilterEvaluationException e ) { e.printStackTrace(); } ResultSet rs = null; PreparedStatement preparedStatement = null; StringBuilder selectRecord = null; try { selectRecord = generateSELECTStatement( formatTypeInISORecordStore.get( CSWConstants.SetOfReturnableElements.brief ), null, formatNum, 0, false, builder ); } catch ( IOException e ) { e.printStackTrace(); } if ( selectRecord != null ) { preparedStatement = conn.prepareStatement( selectRecord.toString() ); } rs = preparedStatement.executeQuery(); List<Integer> deletableDatasets = new ArrayList<Integer>(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append( "DELETE FROM " ); stringBuilder.append( PostGISMappingsISODC.DatabaseTables.datasets.name() ); stringBuilder.append( " WHERE " ).append( PostGISMappingsISODC.CommonColumnNames.id.name() ); stringBuilder.append( " = ?" ); if ( rs != null ) { while ( rs.next() ) { deletableDatasets.add( rs.getInt( 2 ) ); } rs.close(); for ( int i : deletableDatasets ) { stmt = conn.prepareStatement( stringBuilder.toString() ); stmt.setObject( 1, i ); stmt.executeUpdate(); } } affectedIds.addAll( deletableDatasets ); } } if ( stmt != null ) { stmt.close(); } break; } conn.close(); return affectedIds; } /** * This method replaces the text content of an elementknot. * <p> * TODO this is suitable for updates which affect an elementknot that has just one child. <br> * BUG - if there a more childs like in the "keyword"-elementknot. * * @param element * where to start in the OMTree * @param childElements * as an Iterator above all the childElements of the element * @param searchForLocalName * is the name that is searched for. This is the elementknot thats content should be updated. * @param newContent * is the new content that should be updated * @return OMElement */ private OMElement recursiveElementKnotUpdate( OMElement element, Iterator childElements, String searchForLocalName, String newContent ) { Iterator it = element.getChildrenWithLocalName( searchForLocalName ); if ( it.hasNext() ) { OMElement u = null; while ( it.hasNext() ) { u = (OMElement) it.next(); LOG.debug( "rec: " + u.toString() ); u.getFirstElement().setText( newContent ); LOG.debug( "rec2: " + u.toString() ); } return element; } while ( childElements.hasNext() ) { OMElement elem = (OMElement) childElements.next(); recursiveElementKnotUpdate( elem, elem.getChildElements(), searchForLocalName, newContent ); } return element; } /* * (non-Javadoc) * * @see org.deegree.record.persistence.RecordStore#getRecordsById(javax.xml.stream.XMLStreamWriter, * org.deegree.commons.configuration.JDBCConnections, java.util.List) */ @Override public void getRecordById( XMLStreamWriter writer, List<String> idList, URI outputSchema, SetOfReturnableElements elementSetName ) throws SQLException { Connection conn = ConnectionManager.getConnection( connectionId ); int profileFormatNumberOutputSchema = 0; String elementSetNameString = null; for ( QName qName : typeNames.keySet() ) { if ( qName.getNamespaceURI().equals( outputSchema.toString() ) ) { profileFormatNumberOutputSchema = typeNames.get( qName ); } } ResultSet rs = null; for ( String identifier : idList ) { PreparedStatement stmt = null; switch ( elementSetName ) { case brief: elementSetNameString = formatTypeInISORecordStore.get( SetOfReturnableElements.brief ); break; case summary: elementSetNameString = formatTypeInISORecordStore.get( SetOfReturnableElements.summary ); break; case full: elementSetNameString = formatTypeInISORecordStore.get( SetOfReturnableElements.full ); break; default: elementSetNameString = formatTypeInISORecordStore.get( SetOfReturnableElements.brief ); break; } StringBuilder select = new StringBuilder().append( "SELECT recordAlias." ); select.append( PostGISMappingsISODC.CommonColumnNames.data.name() ).append( " FROM " ); select.append( elementSetNameString ).append( " AS recordAlias, " ); select.append( PostGISMappingsISODC.DatabaseTables.datasets.name() ).append( " AS ds, " ); select.append( PostGISMappingsISODC.DatabaseTables.qp_identifier.name() ); select.append( " AS i WHERE recordAlias." ); select.append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ).append( " = ds." ); select.append( PostGISMappingsISODC.CommonColumnNames.id.name() ).append( " AND i." ); select.append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ).append( " = ds." ); select.append( PostGISMappingsISODC.CommonColumnNames.id.name() ).append( " AND i." ); select.append( PostGISMappingsISODC.CommonColumnNames.identifier.name() ).append( " = ? AND recordAlias." ); select.append( PostGISMappingsISODC.CommonColumnNames.format.name() ).append( " = ?;" ); stmt = conn.prepareStatement( select.toString() ); if ( stmt != null ) { stmt.setObject( 1, identifier ); stmt.setInt( 2, profileFormatNumberOutputSchema ); rs = stmt.executeQuery(); writeResultSet( rs, writer ); stmt.close(); } } if ( rs != null ) { rs.close(); } conn.close(); } /** * Prepares the statement to get all the central recordIDs for a statement. * * @param formatType * @param constraint * @param formatNumber * @return * @throws IOException * @throws SQLException */ private PreparedStatement getRequestedIDStatement( String formatType, RecordStoreOptions constraint, int formatNumber, PostGISWhereBuilder builder, Connection conn ) throws IOException, SQLException { StringBuilder s = new StringBuilder(); PreparedStatement stmt = null; StringBuilder constraintExpression = new StringBuilder(); StringBuilder stringBuilder = builder.getWhereClause().getSQL(); if ( stringBuilder.length() != 0 ) { constraintExpression.append( " AND (" ).append( builder.getWhereClause() ).append( ')' ); } else { constraintExpression.append( ' ' ); } s.append( "SELECT " ).append( formatType ).append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ).append( " FROM " ); s.append( PostGISMappingsISODC.DatabaseTables.datasets.name() ).append( ',' ).append( formatType ); for ( PropertyNameMapping propName : builder.getPropNameMappingList() ) { if ( propName.getTable() == null ) { s.append( ' ' ); } else { s.append( ',' ).append( propName.getTable() ).append( ' ' ); } } s.append( " WHERE " ).append( formatType ).append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ).append( '=' ); s.append( PostGISMappingsISODC.DatabaseTables.datasets.name() ).append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.id.name() ).append( " AND " ); s.append( formatType ).append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ); s.append( " >= " ).append( constraint.getStartPosition() ); s.append( " AND " ).append( formatType ).append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.format.name() ).append( '=' ).append( formatNumber ); for ( PropertyNameMapping propName : builder.getPropNameMappingList() ) { if ( propName.getTable() == null ) { s.append( ' ' ); } else { s.append( " AND " ).append( propName.getTable() ).append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ).append( '=' ); s.append( PostGISMappingsISODC.DatabaseTables.datasets.name() ).append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.id.name() ); } } s.append( constraintExpression ); stmt = conn.prepareStatement( s.toString() ); if ( builder.getWhereClause() != null ) { for ( SQLLiteral literal : builder.getWhereClause().getLiterals() ) { LOG.info( "Setting argument: " + literal ); stmt.setObject( 1, literal.getValue() ); } } LOG.debug( "resultSet:" + stmt ); return stmt; } /* * (non-Javadoc) * * @see * org.deegree.record.persistence.RecordStore#getRecordsForTransactionInsertStatement(javax.xml.stream.XMLStreamWriter * ) */ @Override public void getRecordsForTransactionInsertStatement( XMLStreamWriter writer, List<Integer> transactionIds ) throws SQLException, IOException { Connection conn = ConnectionManager.getConnection( connectionId ); ResultSet rsInsertedDatasets = null; StringBuilder s = new StringBuilder().append( " SELECT " ); s.append( formatTypeInISORecordStore.get( SetOfReturnableElements.brief ) ); s.append( '.' ); s.append( PostGISMappingsISODC.CommonColumnNames.data.name() ); s.append( " FROM " ).append( PostGISMappingsISODC.DatabaseTables.datasets.name() ); s.append( ',' ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.brief ) ); s.append( " WHERE " ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.brief ) ); s.append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.fk_datasets.name() ); s.append( '=' ).append( PostGISMappingsISODC.DatabaseTables.datasets.name() ); s.append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.id.name() ); s.append( " AND " ).append( formatTypeInISORecordStore.get( SetOfReturnableElements.brief ) ); s.append( '.' ).append( PostGISMappingsISODC.CommonColumnNames.id.name() ).append( " = ?" ); for ( int i : transactionIds ) { PreparedStatement stmt = conn.prepareStatement( s.toString() ); stmt.setObject( 1, i ); rsInsertedDatasets = stmt.executeQuery(); writeResultSet( rsInsertedDatasets, writer ); stmt.close(); } if ( rsInsertedDatasets != null ) { rsInsertedDatasets.close(); } conn.close(); } /** * This method writes the resultSet from the database with the writer to an XML-output. * * @param resultSet * that should search the backend * @param writer * that writes the data to the output * @throws SQLException */ private void writeResultSet( ResultSet resultSet, XMLStreamWriter writer ) throws SQLException { boolean idIsMatching = false; InputStreamReader isr = null; Charset charset = encoding == null ? Charset.defaultCharset() : Charset.forName( encoding ); while ( resultSet.next() ) { idIsMatching = true; BufferedInputStream bais = new BufferedInputStream( resultSet.getBinaryStream( 1 ) ); try { isr = new InputStreamReader( bais, charset ); } catch ( Exception e ) { LOG.debug( "error: " + e.getMessage(), e ); } readXMLFragment( isr, writer ); } if ( idIsMatching == false ) { throw new InvalidParameterValueException(); } } /** * Reads a valid XML fragment * * @param isr * @param xmlWriter */ private void readXMLFragment( InputStreamReader isr, XMLStreamWriter xmlWriter ) { // XMLStreamReader xmlReaderOut; XMLStreamReader xmlReader; try { // FileOutputStream fout = new FileOutputStream("/home/thomas/Desktop/test.xml"); // XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter( fout ); xmlReader = XMLInputFactory.newInstance().createXMLStreamReader( isr ); // skip START_DOCUMENT xmlReader.nextTag(); // XMLAdapter.writeElement( out, xmlReader ); XMLAdapter.writeElement( xmlWriter, xmlReader ); // fout.close(); xmlReader.close(); } catch ( XMLStreamException e ) { LOG.debug( "error: " + e.getMessage(), e ); } catch ( FactoryConfigurationError e ) { LOG.debug( "error: " + e.getMessage(), e ); } // catch ( FileNotFoundException e ) { // // TODO Auto-generated catch block // LOG.debug( "error: " + e.getMessage(), e ); // } catch ( IOException e ) { // // TODO Auto-generated catch block // LOG.debug( "error: " + e.getMessage(), e ); } }
package com.hp.oo.engine.node.services; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.hp.oo.engine.node.entities.WorkerNode; import com.hp.oo.engine.node.repositories.WorkerNodeRepository; import com.hp.oo.engine.versioning.services.VersionService; import com.hp.oo.enginefacade.Worker; import com.hp.oo.enginefacade.Worker.Status; import org.apache.commons.lang.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; public final class WorkerNodeServiceImpl implements WorkerNodeService, UserDetailsService { static public String RUN_WORKER_PERMISSION = "ROLE_RUN_WORKER"; static public long maxVersionGapAllowed = Long.getLong("max.allowed.version.gap.worker.recovery",2); @Autowired private MessageDigestPasswordEncoder passwordEncoder; @Autowired private WorkerNodeRepository workerNodeRepository; @Autowired private VersionService versionService; @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") @Autowired(required = false) private List<LoginListener> loginListeners; private final static String MSG_RECOVERY_VERSION_NAME = "MSG_RECOVERY_VERSION"; @Override @Transactional @Secured("ROLE_RUN_WORKER") public void keepAlive(String uuid) { WorkerNode worker = readByUUID(uuid); worker.setAckTime(new Date()); long version = versionService.getCurrentVersion(MSG_RECOVERY_VERSION_NAME); worker.setAckVersion(version); if (!worker.getStatus().equals(Status.IN_RECOVERY)) { worker.setStatus(Status.RUNNING); } } @Override @Transactional @Secured("topologyManage") public void create(String uuid, String password, String hostName, String installDir) { WorkerNode worker = new WorkerNode(); worker.setUuid(uuid); worker.setDescription(uuid); worker.setHostName(hostName); worker.setActive(false); worker.setInstallPath(installDir); worker.setStatus(Status.FAILED); password = passwordEncoder.encodePassword(password, uuid); worker.setPassword(password); worker.setGroups(Arrays.asList(WorkerNode.DEFAULT_WORKER_GROUPS)); workerNodeRepository.save(worker); } @Override @Transactional @Secured( "ROLE_USER_ADMIN") public void delete(String uuid) { WorkerNode worker = workerNodeRepository.findByUuid(uuid); if (worker == null) { throw new IllegalStateException("no worker was found by the specified UUID:" + uuid); } workerNodeRepository.delete(worker); } @Transactional @Secured( "topologyManage") public void updateWorkerToDeleted(String uuid) { WorkerNode worker = readByUUID(uuid); if (worker != null ) { if (worker.getStatus() != Status.RUNNING) { worker.setActive(false); worker.setDeleted(true); } else { throw new IllegalArgumentException("The worker is still running and can not be deleted"); } } } @Override @Transactional @Secured({"topologyRead", "topologyManage"}) public List<WorkerNode> readAllNotDeletedWorkers() { return workerNodeRepository.findByDeleted(false); } @Override @Transactional @Secured("ROLE_RUN_WORKER") public void up(String uuid) { if (loginListeners != null) { for (LoginListener listener : loginListeners) { listener.preLogin(uuid); } } keepAlive(uuid); if (loginListeners != null) { for (LoginListener listener : loginListeners) { listener.postLogin(uuid); } } } @Override @Transactional @Secured("ROLE_RUN_WORKER") public void down(String uuid) { //TODO amit levin - logout } @Override @Transactional public void changePassword(String uuid, String password) { WorkerNode worker = readByUUID(uuid); password = passwordEncoder.encodePassword(password, uuid); worker.setPassword(password); } @Override @Transactional(readOnly = true) public WorkerNode readByUUID(String uuid) { WorkerNode worker = workerNodeRepository.findByUuidAndDeleted(uuid, false); if (worker == null) { throw new IllegalStateException("no worker was found by the specified UUID:" + uuid); } return worker; } @Override @Transactional(readOnly = true) @Secured({"topologyRead", "topologyManage"}) public List<WorkerNode> readAllWorkers() { return workerNodeRepository.findAll(); } @Override @Transactional(readOnly = true) public List<String> readNonRespondingWorkers() { long systemVersion = versionService.getCurrentVersion(MSG_RECOVERY_VERSION_NAME); long minVersionAllowed = Math.max( systemVersion - maxVersionGapAllowed , 0); return workerNodeRepository.findNonRespondingWorkers(minVersionAllowed, Status.RECOVERED); } @Override @Transactional(readOnly = true) public List<WorkerNode> readWorkersByActivation(boolean isActive) { return workerNodeRepository.findByActiveAndDeleted(isActive, false); } @Override @Transactional @Secured("topologyManage") public void activate(String uuid) { WorkerNode worker = readByUUID(uuid); worker.setActive(true); } @Override @Transactional @Secured("topologyManage") public void deactivate(String uuid) { WorkerNode worker = readByUUID(uuid); worker.setActive(false); } @Override @Transactional public void updateEnvironmentParams(String uuid, String os, String jvm, String dotNetVersion) { WorkerNode worker = readByUUID(uuid); worker.setOs(os); worker.setJvm(jvm); worker.setDotNetVersion(dotNetVersion); } @Override @Transactional public void updateDescription(String uuid, String description) { WorkerNode worker = readByUUID(uuid); worker.setDescription(description); } @Override @Transactional public void updateStatus(String uuid, Worker.Status status) { WorkerNode worker = readByUUID(uuid); worker.setStatus(status); } @Override @Transactional(readOnly = true) public List<String> readAllWorkerGroups() { return workerNodeRepository.findGroups(); } @Override @Transactional(readOnly = true) public List<String> readWorkerGroups(String uuid){ WorkerNode node = readByUUID(uuid); ArrayList<String> res = new ArrayList<>(); res.addAll(node.getGroups()); return res; } @Override @Transactional @Secured("topologyManage") public void updateWorkerGroups(String uuid, String... groupNames) { WorkerNode worker = readByUUID(uuid); List<String> groups = groupNames!=null? Arrays.asList(groupNames): Collections.<String>emptyList(); worker.setGroups(groups); } @Override @Transactional(readOnly = true) public List<WorkerNode> readWorkersByGroup(String groupName, boolean onlyForActiveWorkers) { List<WorkerNode> workers = workerNodeRepository.findByGroupsAndDeleted(groupName, false); if (onlyForActiveWorkers) { List<WorkerNode> activeWorkers = new ArrayList<>(workers.size()); for (WorkerNode worker : workers) { if (worker.isActive()) { activeWorkers.add(worker); } } return activeWorkers; } else return workers; } @Override @Transactional(readOnly = true) public Multimap<String, String> readGroupWorkersMap(boolean onlyForActiveWorkers) { Multimap<String, String> result = ArrayListMultimap.create(); List<WorkerNode> workers; if (onlyForActiveWorkers) workers = workerNodeRepository.findByActiveAndDeleted(true, false); else workers = workerNodeRepository.findAll(); for (WorkerNode worker : workers) { for (String groupName : worker.getGroups()) { result.put(groupName, worker.getUuid()); } } return result; } @Override @Transactional(readOnly = true) public Multimap<String, String> readGroupWorkersMapActiveAndRunning() { Multimap<String, String> result = ArrayListMultimap.create(); List<WorkerNode> workers; workers = workerNodeRepository.findByActiveAndStatusAndDeleted(true, Status.RUNNING, false); for (WorkerNode worker : workers) { for (String groupName : worker.getGroups()) { result.put(groupName, worker.getUuid()); } } return result; } @Override @Transactional @Secured("topologyManage") public void addGroupToWorker(String workerUuid, String group) { WorkerNode worker = readByUUID(workerUuid); List<String> groups = new ArrayList<>(worker.getGroups()); groups.add(group); worker.setGroups(groups); } @Override @Transactional @Secured({"topologyRead", "topologyManage"}) public void removeGroupFromWorker(String workerUuid, String group) { WorkerNode worker = readByUUID(workerUuid); List<String> groups = new ArrayList<>(worker.getGroups()); groups.remove(group); if (groups.size() == 0) throw new IllegalStateException("Can't leave worker without any group !"); worker.setGroups(groups); } @Override @Transactional(readOnly = true) public List<String> readWorkerGroups(List<String> groups) { return workerNodeRepository.findGroups(groups); } @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { WorkerNode worker; try { worker = readByUUID(username); } catch (IllegalStateException e) { throw new UsernameNotFoundException("Unknown user :" + username); } return new User(worker.getUuid(), worker.getPassword(), Arrays.asList( new SimpleGrantedAuthority(RUN_WORKER_PERMISSION), new SimpleGrantedAuthority("ROLE_NODE"), new SimpleGrantedAuthority("ROLE_OO"), new SimpleGrantedAuthority("login") )); } @Override @Transactional public void lock(String uuid) { Validate.notEmpty(uuid, "Worker UUID is null or empty"); workerNodeRepository.lockByUuid(uuid); workerNodeRepository.flush(); } }
package org.fedorahosted.flies.webtrans.client; import java.util.ArrayList; import java.util.HashMap; import org.fedorahosted.flies.gwt.model.DocName; import org.fedorahosted.flies.gwt.model.DocumentId; import org.fedorahosted.flies.webtrans.client.ui.HasTreeNodes; import org.fedorahosted.flies.webtrans.client.ui.TreeNode; import org.fedorahosted.flies.webtrans.client.ui.TreeNodeMapper; public class FlatFolderDocNameMapper implements TreeNodeMapper<DocumentId, DocName> { public void addToTree(HasTreeNodes<DocumentId, DocName> tree, ArrayList<DocName> docNames, boolean openFolderNodes) { HashMap<String, TreeNode<DocName>> folderNodes = new HashMap<String, TreeNode<DocName>>(); for (DocName docName : docNames) { String path = docName.getPath(); TreeNode<DocName> item; if (path == null || path.length() == 0 || "/".equals(path)) { item = tree.addItem(docName.getName()); } else { TreeNode<DocName> folder = folderNodes.get(path); if (folder == null) { // TODO create intervening folders for a hierarchical impl folder = tree.addItem(path); folderNodes.put(path, folder); } item = folder.addItem(docName.getName()); folder.setState(openFolderNodes); // TreeItem can't open a node until it has children } tree.nodeAdded(docName.getId(), item); item.setObject(docName); } } @Override public boolean passFilter(DocName docName, String filter) { return docName.getName().toLowerCase().contains(filter.toLowerCase()); } }
package org.fedorahosted.flies.webtrans.client; import org.fedorahosted.flies.webtrans.client.Application.WindowResizeEvent; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.place.Place; import net.customware.gwt.presenter.client.place.PlaceRequest; import net.customware.gwt.presenter.client.widget.WidgetDisplay; import net.customware.gwt.presenter.client.widget.WidgetPresenter; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.core.client.GWT; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.HasWidgets; import com.google.inject.Inject; public class WestNavigationPresenter extends WidgetPresenter<WestNavigationPresenter.Display>{ public static final Place PLACE = new Place("WestNavigationPresenter"); //private final DispatchAsync dispatcher; public interface Display extends WidgetDisplay { HasWidgets getWidgets(); } private final WorkspaceUsersPresenter workspaceUsersPresenter; private final DocumentListPresenter documentListPresenter; private final TransUnitInfoPresenter transUnitInfoPresenter; @Inject public WestNavigationPresenter(final Display display, final EventBus eventBus, WorkspaceUsersPresenter workspaceUsersPresenter, DocumentListPresenter documentListPresenter,TransUnitInfoPresenter transUnitInfoPresenter){//, final DispatchAsync dispatcher) { super(display, eventBus); //this.dispatcher = dispatcher; this.workspaceUsersPresenter = workspaceUsersPresenter; this.documentListPresenter = documentListPresenter; this.transUnitInfoPresenter = transUnitInfoPresenter; bind(); } @Override public Place getPlace() { return PLACE; } @Override protected void onBind() { // Disabled: This pushes the footer (DockPanel.SOUTH) off the bottom of the visible window // eventBus.addHandler(WindowResizeEvent.getType(), new ResizeHandler() { // @Override // public void onResize(ResizeEvent event) { // Log.info("handling resize in LeftNavigationPresenter"); // display.asWidget().setHeight(event.getHeight() + "px"); display.asWidget().setHeight("100%"); display.getWidgets().add(documentListPresenter.getDisplay().asWidget()); display.getWidgets().add(transUnitInfoPresenter.getDisplay().asWidget()); display.getWidgets().add(workspaceUsersPresenter.getDisplay().asWidget()); documentListPresenter.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { Log.info("selected document: "+event.getValue()); } }); } @Override protected void onPlaceRequest(PlaceRequest request) { // TODO Auto-generated method stub } @Override protected void onUnbind() { documentListPresenter.unbind(); workspaceUsersPresenter.unbind(); } @Override public void refreshDisplay() { // TODO Auto-generated method stub } @Override public void revealDisplay() { // TODO Auto-generated method stub } }
package org.fedorahosted.flies.webtrans.editor; import com.google.inject.Inject; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.place.Place; import net.customware.gwt.presenter.client.place.PlaceRequest; import net.customware.gwt.presenter.client.widget.WidgetDisplay; import net.customware.gwt.presenter.client.widget.WidgetPresenter; public class WebTransEditorPresenter extends WidgetPresenter<WebTransEditorPresenter.Display>{ public static final Place PLACE = new Place("WebTransEditor"); public interface Display extends WidgetDisplay{ } @Inject public WebTransEditorPresenter(Display display, EventBus eventBus) { super(display, eventBus); bind(); } @Override public Place getPlace() { return PLACE; } @Override protected void onBind() { } @Override protected void onPlaceRequest(PlaceRequest request) { } @Override protected void onUnbind() { } @Override public void refreshDisplay() { } @Override public void revealDisplay() { } }