gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* Copyright (C) 2001, 2006 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. */ package gov.nasa.worldwind.geom; import gov.nasa.worldwind.util.*; /** * @author tag * @version $Id: Position.java 12876 2009-12-09 21:48:41Z dcollins $ */ public class Position extends LatLon { public static final Position ZERO = new Position(Angle.ZERO, Angle.ZERO, 0d); public final double elevation; public static Position fromRadians(double latitude, double longitude, double elevation) { return new Position(Angle.fromRadians(latitude), Angle.fromRadians(longitude), elevation); } public static Position fromDegrees(double latitude, double longitude, double elevation) { return new Position(Angle.fromDegrees(latitude), Angle.fromDegrees(longitude), elevation); } public Position(Angle latitude, Angle longitude, double elevation) { super(latitude, longitude); this.elevation = elevation; } public Position(LatLon latLon, double elevation) { super(latLon); this.elevation = elevation; } /** * Obtains the elevation of this position * * @return this position's elevation */ public final double getElevation() { return this.elevation; } public final LatLon getLatLon() { return new LatLon(this); } public Position add(Position that) { Angle lat = Angle.normalizedLatitude(this.latitude.add(that.latitude)); Angle lon = Angle.normalizedLongitude(this.longitude.add(that.longitude)); return new Position(lat, lon, this.elevation + that.elevation); } public Position subtract(Position that) { Angle lat = Angle.normalizedLatitude(this.latitude.subtract(that.latitude)); Angle lon = Angle.normalizedLongitude(this.longitude.subtract(that.longitude)); return new Position(lat, lon, this.elevation - that.elevation); } /** * Returns the linear interpolation of <code>value1</code> and <code>value2</code>, treating the geographic * locations as simple 2D coordinate pairs, and treating the elevation values as 1D scalars. * * @param amount the interpolation factor * @param value1 the first position. * @param value2 the second position. * * @return the linear interpolation of <code>value1</code> and <code>value2</code>. * * @throws IllegalArgumentException if either position is null. */ public static Position interpolate(double amount, Position value1, Position value2) { if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (amount < 0) return value1; else if (amount > 1) return value2; LatLon latLon = LatLon.interpolate(amount, value1, value2); // Elevation is independent of geographic interpolation method (i.e. rhumb, great-circle, linear), so we // interpolate elevation linearly. double elevation = WWMath.mix(amount, value1.getElevation(), value2.getElevation()); return new Position(latLon, elevation); } /** * Returns the an interpolated location along the great-arc between <code>value1</code> and <code>value2</code>. The * position's elevation components are linearly interpolated as a simple 1D scalar value. The interpolation factor * <code>amount</code> defines the weight given to each value, and is clamped to the range [0, 1]. If <code>a</code> * is 0 or less, this returns <code>value1</code>. If <code>amount</code> is 1 or more, this returns * <code>value2</code>. Otherwise, this returns the position on the great-arc between <code>value1</code> and * <code>value2</code> with a linearly interpolated elevation component, and corresponding to the specified * interpolation factor. * * @param amount the interpolation factor * @param value1 the first position. * @param value2 the second position. * * @return an interpolated position along the great-arc between <code>value1</code> and <code>value2</code>, with a * linearly interpolated elevation component. * * @throws IllegalArgumentException if either location is null. */ public static Position interpolateGreatCircle(double amount, Position value1, Position value2) { if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } LatLon latLon = LatLon.interpolateGreatCircle(amount, value1, value2); // Elevation is independent of geographic interpolation method (i.e. rhumb, great-circle, linear), so we // interpolate elevation linearly. double elevation = WWMath.mix(amount, value1.getElevation(), value2.getElevation()); return new Position(latLon, elevation); } /** * Returns the an interpolated location along the rhumb line between <code>value1</code> and <code>value2</code>. * The position's elevation components are linearly interpolated as a simple 1D scalar value. The interpolation * factor <code>amount</code> defines the weight given to each value, and is clamped to the range [0, 1]. If * <code>a</code> is 0 or less, this returns <code>value1</code>. If <code>amount</code> is 1 or more, this returns * <code>value2</code>. Otherwise, this returns the position on the rhumb line between <code>value1</code> and * <code>value2</code> with a linearly interpolated elevation component, and corresponding to the specified * interpolation factor. * * @param amount the interpolation factor * @param value1 the first position. * @param value2 the second position. * * @return an interpolated position along the great-arc between <code>value1</code> and <code>value2</code>, with a * linearly interpolated elevation component. * * @throws IllegalArgumentException if either location is null. */ public static Position interpolateRhumb(double amount, Position value1, Position value2) { if (value1 == null || value2 == null) { String message = Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } LatLon latLon = LatLon.interpolateRhumb(amount, value1, value2); // Elevation is independent of geographic interpolation method (i.e. rhumb, great-circle, linear), so we // interpolate elevation linearly. double elevation = WWMath.mix(amount, value1.getElevation(), value2.getElevation()); return new Position(latLon, elevation); } public static boolean positionsCrossDateLine(Iterable<? extends Position> positions) { if (positions == null) { String msg = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } Position pos = null; for (Position posNext : positions) { if (pos != null) { // A segment cross the line if end pos have different longitude signs // and are more than 180 degress longitude apart if (Math.signum(pos.getLongitude().degrees) != Math.signum(posNext.getLongitude().degrees)) { double delta = Math.abs(pos.getLongitude().degrees - posNext.getLongitude().degrees); if (delta > 180 && delta < 360) return true; } } pos = posNext; } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Position position = (Position) o; //noinspection RedundantIfStatement if (Double.compare(position.elevation, elevation) != 0) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); long temp; temp = elevation != +0.0d ? Double.doubleToLongBits(elevation) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public String toString() { return "(" + this.latitude.toString() + ", " + this.longitude.toString() + ", " + this.elevation + ")"; } }
package net.edzard.kinetic; import java.util.ArrayList; import java.util.List; /** * Defines a path using a variety of drawing commands. * Paths are used to define custom shapes. The path object uses command chaining, which enables you to specify complete paths by using combined statements. * For example: new Path().beginPath().moveTo(new Vector2d(200,50)).lineTo(new Vector2d(420,80)).quadraticCurveTo(new Vector2d(300, 100), new Vector2d(260, 170)).closePath(); * @author Ed * @see CustomShape */ public class Path { /** * The type of a path command * @author Ed */ public enum CommandType { UNKNOWN, BEGIN, MOVE, CLOSE, LINE, QUADRATIC, BEZIER, ARCTO, ARC, RECT } /** * Base class for all path commands * @author Ed */ public class Command { public CommandType type = CommandType.UNKNOWN; } /** * Command for beginning a path * @author Ed */ public class BeginPathCommand extends Command { /** * Default Ctor */ public BeginPathCommand() { type = CommandType.BEGIN; } } /** * Command for creating a new subpath with the given point. * No connection to the previous position is made. * @author Ed */ public class MoveToCommand extends Command { /** A position */ private Vector2d pos; /** * Parametrized Ctor. * @param pos A new position value */ public MoveToCommand(Vector2d pos) { type = CommandType.MOVE; this.pos = pos; } /** * Retrieve the position. * @return The position value */ public Vector2d getPosition() { return pos; } /** * Assign a position value. * @param pos A position value */ public void setPosition(Vector2d pos) { this.pos = pos; } } /** * Command for marking the current subpath as closed, and starting a new subpath using the same point as the one for the end of the newly closed subpath. * @author Ed */ public class ClosePathCommand extends Command { /** * Default Ctor. */ public ClosePathCommand() { type = CommandType.CLOSE; } } /** * Command for adding the given point to the current subpath and connecting it to the previous one by a straight line. * @author Ed */ public class LineToCommand extends Command { /** A position to line to */ private Vector2d pos; /** * Parametrized Ctor. * @param pos A position to draw a line to */ public LineToCommand(Vector2d pos) { super(); type = CommandType.LINE; this.pos = pos; } /** * Retrieve the position. * @return The position where to draw a line to */ public Vector2d getPosition() { return pos; } /** * Assign a position. * @param pos A position to draw a line to */ public void setPosition(Vector2d pos) { this.pos = pos; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "LineTo" + pos; } } /** * Command for adding the given point to the current subpath and connecting to the previous one by a quadratic Bezier curve with one given control point. * @author Ed */ public class QuadraticCurveCommand extends Command { /** The control point */ private Vector2d cp; /** The position */ private Vector2d pos; /** * Parametrized Ctor. * @param cp The control point * @param pos The position */ public QuadraticCurveCommand(Vector2d cp, Vector2d pos) { super(); type = CommandType.QUADRATIC; this.pos = pos; this.cp = cp; } /** * Retrieve the position. * @return The position where to draw a curve to */ public Vector2d getPosition() { return pos; } /** * Assign a position. * @param pos A position to draw a curve to */ public void setPosition(Vector2d pos) { this.pos = pos; } /** * Retrieve the control point. * @return The control point for the curve */ public Vector2d getControlPoint() { return cp; } /** * Assign a control point. * @param cp A control point for the curve */ public void setControlPoint(Vector2d cp) { this.cp = cp; } } /** * Command for adding the given point to the current subpath and connecting to the previous one by a cubic Bezier curve with two given control points. * @author Ed */ public class BezierCurveCommand extends Command { private Vector2d cp1; private Vector2d cp2; private Vector2d pos; /** * Parametrized Ctor * @param cp1 Control point 1 * @param cp2 Control point 2 * @param pos The position to draw a curve to */ public BezierCurveCommand(Vector2d cp1, Vector2d cp2, Vector2d pos) { super(); type = CommandType.BEZIER; this.pos = pos; this.cp1 = cp1; this.cp2 = cp2; } /** * Retrieve the position. * @return The position where to draw a curve to */ public Vector2d getPosition() { return pos; } /** * Assign a position. * @param pos A position to draw a curve to */ public void setPosition(Vector2d pos) { this.pos = pos; } /** * Retrieve the control point 1. * @return The control point 1 for the curve */ public Vector2d getControlPoint1() { return cp1; } /** * Assign a the control point 1. * @param cp1 The control point 1 for the curve */ public void setControlPoint1(Vector2d cp1) { this.cp1 = cp1; } /** * Retrieve the control point 2. * @return The control point 2 for the curve */ public Vector2d getControlPoint2() { return cp2; } /** * Assign a the control point 2. * @param cp2 The control point 2 for the curve */ public void setControlPoint2(Vector2d cp2) { this.cp2 = cp2; } } /** * Command for adding an arc with the given two position points and radius to the current subpath and connecting it to the previous point by a straight line. * @author Ed */ public class ArcToCommand extends Command { /** First position */ private Vector2d pos1; /** Second position */ private Vector2d pos2; /** Radius of arc */ double radius; /** * Parametrized Ctor. * @param pos1 The first position * @param pos2 The second position * @param radius The arc's radius */ public ArcToCommand(Vector2d pos1, Vector2d pos2, double radius) { super(); type = CommandType.ARCTO; this.pos1 = pos1; this.pos2 = pos2; this.radius = radius; } /** * Retrieve the first position point. * @return A position point for drawing the arc */ public Vector2d getPosition1() { return pos1; } /** * Assign the first position point. * @param pos A position point for drawing the arc */ public void setPosition1(Vector2d pos1) { this.pos1 = pos1; } /** * Retrieve the second position point. * @return A position point for drawing the arc */ public Vector2d getPosition2() { return pos2; } /** * Assign the second position point. * @param pos A position point for drawing the arc */ public void setPosition2(Vector2d pos2) { this.pos2 = pos2; } /** * Retrieve the radius. * @return The arc's radius */ public double getRadius() { return radius; } /** * Assign the radius. * @param radius A new radius for the arc */ public void setRadius(double radius) { this.radius = radius; } } /** * Command for adding points to the subpath such that the arc described by the circumference of the circle described by the arguments, * starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, * connected to the previous point by a straight line. This sounds complicated. It's not. Try it. * @author Ed */ public class ArcCommand extends Command { /** The position */ private Vector2d pos; /** The arc's radius */ private double radius; /** The start angle */ private double startAngle; /** The end angle */ private double endAngle; /** Controls direction */ private boolean clockwise; /** * Parametrized Ctor. * @param pos The initial position * @param radius Arc's radius * @param startAngle The start angle * @param endAngle The end angle * @param clockwise Control direction. True is clockwise, False is anti-clockwise */ public ArcCommand(Vector2d pos, double radius, double startAngle, double endAngle, boolean clockwise) { super(); type = CommandType.ARC; this.pos = pos; this.radius = radius; this.startAngle = startAngle; this.endAngle = endAngle; this.clockwise = clockwise; } /** * Retrieve the position. * @return The position for drawing the arc */ public Vector2d getPosition() { return pos; } /** * Assign a position. * @param pos A position for drawing the arc */ public void setPosition(Vector2d pos) { this.pos = pos; } /** * Retrieve the radius. * @return The arc's radius */ public double getRadius() { return radius; } /** * Assign the radius. * @param radius A new radius for the arc */ public void setRadius(double radius) { this.radius = radius; } /** * Retrieve start angle. * @return The start angle */ public double getStartAngle() { return startAngle; } /** * Assign a start angle. * @param startAngle The start angle */ public void setStartAngle(double startAngle) { this.startAngle = startAngle; } /** * Retrieve end angle. * @return The end angle */ public double getEndAngle() { return endAngle; } /** * Assign an end angle. * @param endAngle The end angle */ public void setEndAngle(double endAngle) { this.endAngle = endAngle; } /** * Check if the drawing direction is clockwise. * @return True, if it is clockwise. False, otherwise. */ public boolean isClockwise() { return clockwise; } /** * Set the draweing direction * @param clockwise Set to true if drawing should occur clockwise. Otherwise, set to False. */ public void setClockwise(boolean clockwise) { this.clockwise = clockwise; } } /** * Command for adding a new closed subpath to the path, representing the given rectangle. * @author Ed */ public class RectCommand extends Command { /** Definition of the rectangle */ private Box2d box; /** * Parametrized Ctor. * @param box Rectangle extents */ public RectCommand(Box2d box) { super(); type = CommandType.RECT; this.box = box; } /** * Assign extents of the rectangle. * @return The size definition */ public Box2d getBox() { return box; } /** * Retrieve extents of the rectangle * @param box The extents */ public void setBox(Box2d box) { this.box = box; } } // TODO: Ellipse? /** Holds the commands that make up this path */ private List<Command> commands; /** * Default Ctor. */ public Path() { this.commands = new ArrayList<Command>(); } /** * Begins a path. * @return this (for command chaining) */ public Path beginPath() { commands.add(new BeginPathCommand()); return this; } /** * Clears the path. * @return this (for command chaining) */ public Path clear() { commands.clear(); return this; } /** * Moves the current position to a new one (without drawing a line). * @param pos The position to move to * @return this (for command chaining) */ public Path moveTo(Vector2d pos) { commands.add(new MoveToCommand(pos)); return this; } /** * Closes a path. * Multiple sub-paths can be created on a single path. * @return this (for command chaining) */ public Path closePath() { commands.add(new ClosePathCommand()); return this; } /** * Draws a line to a given position. * @param pos The position to draw a line to * @return this (for command chaining) */ public Path lineTo(Vector2d pos) { commands.add(new LineToCommand(pos)); return this; } /** * Adding the given position to the current path and connects it to the previous one by a quadratic Bezier curve with one given control point. * @param pos The new position to add to the path * @param cp The single control point for the bezier curve * @return this (for command chaining) */ public Path quadraticCurveTo(Vector2d pos, Vector2d cp) { commands.add(new QuadraticCurveCommand(pos, cp)); return this; } /** * Adding the given position to the current path and connects it to the previous one by a quadratic Bezier curve with two given control point. * @param pos The new position to add to the path * @param cp1 The first control point * @param cp2 The second control point * @return this (for command chaining) */ public Path bezierCurveTo(Vector2d pos, Vector2d cp1, Vector2d cp2) { commands.add(new BezierCurveCommand(pos, cp1, cp2)); return this; } /** * Adds an arc with the given two position points and radius to the current path and connects it to the previous position by a straight line. * @param pos1 First position point for the arc * @param pos2 Second position point for the arc * @param radius The arc's radius * @return this (for command chaining) */ public Path arcTo(Vector2d pos1, Vector2d pos2, double radius) { commands.add(new ArcToCommand(pos1, pos2, radius)); return this; } /** * Adds an arc with the given position to the path such that the circumference of the circle described by the arguments, * starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), * is added to the path, connected to the previous position by a straight line. This sounds complicated. It's not. Try it. * @param pos Postion for the arc * @param radius Radius of the arc * @param startAngle Start angle of the arc * @param endAngle End angle for the arc * @param clockwise Direction for drawing of the arc. True means clockwise. False means anti-clockwise. * @return this (for command chaining) */ public Path arc(Vector2d pos, double radius, double startAngle, double endAngle, boolean clockwise) { commands.add(new ArcCommand(pos, radius, startAngle, endAngle, clockwise)); return this; } /** * Adds a new closed subpath to the path, representing a given rectangle. * @param box The rectangle to add * @return this (for command chaining) */ public Path rect(Box2d box) { commands.add(new RectCommand(box)); return this; } /** * Retrieve the commands that make up this path. * @return The current list of path commands */ public List<Command> getCommands() { return commands; } /** * Convert this path into the SVG standard path. * @return The current list of path commands */ public String toSVGPath() { StringBuilder sb = new StringBuilder(); for(Command c : commands) { switch (c.type) { case BEGIN: // do nothing break; case CLOSE: sb.append('Z'); break; case LINE: LineToCommand ltc = (LineToCommand)c; sb.append("L" + ltc.getPosition().x + ',' + ltc.getPosition().y); break; case MOVE: MoveToCommand mtc = (MoveToCommand)c; sb.append("M" + mtc.getPosition().x + ',' + mtc.getPosition().y); break; default: throw new UnsupportedOperationException(c.type.name()); } } return sb.toString(); } }
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.commonjava.indy.pkg.maven.content; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.repository.metadata.Metadata; import org.apache.maven.artifact.repository.metadata.Plugin; import org.apache.maven.artifact.repository.metadata.SnapshotVersion; import org.apache.maven.artifact.repository.metadata.Versioning; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader; import org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Writer; import org.commonjava.atlas.maven.ident.ref.SimpleTypeAndClassifier; import org.commonjava.atlas.maven.ident.ref.TypeAndClassifier; import org.commonjava.atlas.maven.ident.util.ArtifactPathInfo; import org.commonjava.atlas.maven.ident.util.SnapshotUtils; import org.commonjava.atlas.maven.ident.util.VersionUtils; import org.commonjava.atlas.maven.ident.version.SingleVersion; import org.commonjava.atlas.maven.ident.version.part.SnapshotPart; import org.commonjava.cdi.util.weft.DrainingExecutorCompletionService; import org.commonjava.cdi.util.weft.ExecutorConfig; import org.commonjava.cdi.util.weft.Locker; import org.commonjava.cdi.util.weft.WeftExecutorService; import org.commonjava.cdi.util.weft.WeftManaged; import org.commonjava.indy.IndyWorkflowException; import org.commonjava.indy.content.DirectContentAccess; import org.commonjava.indy.content.MergedContentAction; import org.commonjava.indy.content.StoreResource; import org.commonjava.indy.core.content.AbstractMergedContentGenerator; import org.commonjava.indy.core.content.group.GroupMergeHelper; import org.commonjava.indy.data.StoreDataManager; import org.commonjava.o11yphant.metrics.annotation.Measure; import org.commonjava.indy.model.core.ArtifactStore; import org.commonjava.indy.model.core.Group; import org.commonjava.indy.model.core.StoreKey; import org.commonjava.indy.model.core.StoreType; import org.commonjava.indy.pkg.maven.content.group.MavenMetadataMerger; import org.commonjava.indy.pkg.maven.content.group.MavenMetadataProvider; import org.commonjava.indy.util.LocationUtils; import org.commonjava.maven.galley.event.EventMetadata; import org.commonjava.maven.galley.maven.parse.GalleyMavenXMLException; import org.commonjava.maven.galley.maven.parse.XMLInfrastructure; import org.commonjava.maven.galley.maven.spi.type.TypeMapper; import org.commonjava.maven.galley.model.ConcreteResource; import org.commonjava.maven.galley.model.Transfer; import org.commonjava.maven.galley.model.TransferOperation; import org.commonjava.maven.galley.model.TypeMapping; import org.commonjava.maven.galley.spi.nfc.NotFoundCache; import org.commonjava.o11yphant.trace.TraceManager; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.annotation.PostConstruct; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.stream.Collectors; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.io.IOUtils.closeQuietly; import static org.commonjava.atlas.maven.ident.util.SnapshotUtils.LOCAL_SNAPSHOT_VERSION_PART; import static org.commonjava.atlas.maven.ident.util.SnapshotUtils.generateUpdateTimestamp; import static org.commonjava.atlas.maven.ident.util.SnapshotUtils.getCurrentTimestamp; import static org.commonjava.indy.core.content.group.GroupMergeHelper.GROUP_METADATA_EXISTS; import static org.commonjava.indy.core.content.group.GroupMergeHelper.GROUP_METADATA_GENERATED; import static org.commonjava.indy.core.ctl.PoolUtils.detectOverloadVoid; import static org.commonjava.maven.galley.io.SpecialPathConstants.HTTP_METADATA_EXT; import static org.commonjava.maven.galley.util.PathUtils.normalize; import static org.commonjava.maven.galley.util.PathUtils.parentPath; import static org.commonjava.o11yphant.trace.TraceManager.addFieldToActiveSpan; public class MavenMetadataGenerator extends AbstractMergedContentGenerator { private static final String ARTIFACT_ID = "artifactId"; private static final String GROUP_ID = "groupId"; private static final String VERSION = "version"; private static final String LAST_UPDATED = "lastUpdated"; private static final String TIMESTAMP = "timestamp"; private static final String BUILD_NUMBER = "buildNumber"; private static final String EXTENSION = "extension"; private static final String VALUE = "value"; private static final String UPDATED = "updated"; private static final String LOCAL_COPY = "localCopy"; private static final String LATEST = "latest"; private static final String RELEASE = "release"; private static final String CLASSIFIER = "classifier"; @Inject private MetadataCacheManager cacheManager; private static final Set<String> HANDLED_FILENAMES = Collections.unmodifiableSet( new HashSet<String>() { { add( MavenMetadataMerger.METADATA_NAME ); add( MavenMetadataMerger.METADATA_MD5_NAME ); add( MavenMetadataMerger.METADATA_SHA_NAME ); add( MavenMetadataMerger.METADATA_SHA256_NAME ); } private static final long serialVersionUID = 1L; } ); @Inject private XMLInfrastructure xml; @Inject private TypeMapper typeMapper; @Inject private MavenMetadataMerger merger; @Inject private Instance<MavenMetadataProvider> metadataProviderInstances; private List<MavenMetadataProvider> metadataProviders; @Inject @WeftManaged @ExecutorConfig( named="maven-metadata-generator", threads=50, loadSensitive = ExecutorConfig.BooleanLiteral.TRUE, maxLoadFactor = 10000 ) private WeftExecutorService mavenMDGeneratorService; // don't need to inject since it's only used internally private final Locker<String> mergerLocks = new Locker<>(); private static final int THREAD_WAITING_TIME_SECONDS = 300; protected MavenMetadataGenerator() { } public MavenMetadataGenerator( final DirectContentAccess fileManager, final StoreDataManager storeManager, final XMLInfrastructure xml, final TypeMapper typeMapper, final MavenMetadataMerger merger, final GroupMergeHelper mergeHelper, final NotFoundCache nfc, WeftExecutorService mavenMDGeneratorService, final MergedContentAction... mergedContentActions ) { super( fileManager, storeManager, mergeHelper, nfc, mergedContentActions ); this.xml = xml; this.typeMapper = typeMapper; this.merger = merger; this.mavenMDGeneratorService = mavenMDGeneratorService; start(); } @PostConstruct public void start() { metadataProviders = new ArrayList<>(); if ( metadataProviderInstances != null ) { metadataProviderInstances.forEach( provider -> metadataProviders.add( provider ) ); } } public void clearAllMerged( ArtifactStore store, String...paths ) { super.clearAllMerged( store, paths ); } @Override @Measure public Transfer generateFileContent( final ArtifactStore store, final String path, final EventMetadata eventMetadata ) throws IndyWorkflowException { // metadata merging is something else...don't handle it here. if ( StoreType.group == store.getKey().getType() ) { return null; } if ( !canProcess( path ) ) { return null; } boolean generated; // TODO: Generation of plugin metadata files (groupId-level) is harder, and requires cracking open the jar file // This is because that's the only place the plugin prefix can be reliably retrieved from. // regardless, we will need this first level of listings. What we do with it will depend on the logic below... final String parentPath = Paths.get( path ) .getParent() .toString(); List<StoreResource> firstLevel; try { firstLevel = fileManager.listRaw( store, parentPath ); } catch ( final IndyWorkflowException e ) { logger.error( String.format( "SKIP: Failed to generate maven-metadata.xml from listing of directory contents for: %s under path: %s", store, parentPath ), e ); return null; } String toGenPath = path; if ( !path.endsWith( MavenMetadataMerger.METADATA_NAME ) ) { toGenPath = normalize( normalize( parentPath( toGenPath ) ), MavenMetadataMerger.METADATA_NAME ); } ArtifactPathInfo snapshotPomInfo = null; if ( parentPath.endsWith( LOCAL_SNAPSHOT_VERSION_PART ) ) { // If we're in a version directory, first-level listing should include a .pom file for ( final StoreResource resource : firstLevel ) { if ( resource.getPath().endsWith( ".pom" ) ) { snapshotPomInfo = ArtifactPathInfo.parse( resource.getPath() ); break; } } } if ( snapshotPomInfo != null ) { logger.debug( "Generating maven-metadata.xml for snapshots, store: {}", store.getKey() ); generated = writeSnapshotMetadata( snapshotPomInfo, firstLevel, store, toGenPath, eventMetadata ); } else { logger.debug( "Generating maven-metadata.xml for releases, store: {}", store.getKey() ); generated = writeVersionMetadata( firstLevel, store, toGenPath, eventMetadata ); } logger.debug( "[Result] Generating maven-metadata.xml for store: {}, result: {}", store.getKey(), generated ); return generated ? fileManager.getTransfer( store, path ) : null; } @Override public List<StoreResource> generateDirectoryContent( final ArtifactStore store, final String path, final List<StoreResource> existing, final EventMetadata eventMetadata ) throws IndyWorkflowException { final StoreResource mdResource = new StoreResource( LocationUtils.toLocation( store ), Paths.get( path, MavenMetadataMerger.METADATA_NAME ) .toString() ); if ( existing.contains( mdResource ) ) { return null; } int pathElementsCount = StringUtils.strip( path, "/" ).split( "/" ).length; // if there is a possibility we are listing an artifactId if ( pathElementsCount >= 2 ) { // regardless, we will need this first level of listings. What we do with it will depend on the logic below... final List<StoreResource> firstLevelFiles = fileManager.listRaw( store, path, eventMetadata ); ArtifactPathInfo samplePomInfo = null; for ( final StoreResource topResource : firstLevelFiles ) { final String topPath = topResource.getPath(); if ( topPath.endsWith( ".pom" ) ) { samplePomInfo = ArtifactPathInfo.parse( topPath ); break; } } // if this dir does not contain a pom check if a subdir contain a pom if ( samplePomInfo == null ) { List<String> firstLevelDirs = firstLevelFiles.stream() .map( ConcreteResource::getPath ) .filter( (subpath) -> subpath.endsWith( "/" ) ) .collect( Collectors.toList() ); final Map<String, List<StoreResource>> secondLevelMap = fileManager.listRaw( store, firstLevelDirs, eventMetadata ); nextTopResource: for ( final String topPath : firstLevelDirs ) { final List<StoreResource> secondLevelListing = secondLevelMap.get( topPath ); for ( final StoreResource fileResource : secondLevelListing ) { if ( fileResource.getPath() .endsWith( ".pom" ) ) { samplePomInfo = ArtifactPathInfo.parse( fileResource.getPath() ); break nextTopResource; } } } } // TODO: Generation of plugin metadata files (groupId-level) is harder, and requires cracking open the jar file // This is because that's the only place the plugin prefix can be reliably retrieved from. // We won't worry about this for now. if ( samplePomInfo != null ) { final List<StoreResource> result = new ArrayList<>(); result.add( mdResource ); result.add( new StoreResource( LocationUtils.toLocation( store ), Paths.get( path, MavenMetadataMerger.METADATA_MD5_NAME ) .toString() ) ); result.add( new StoreResource( LocationUtils.toLocation( store ), Paths.get( path, MavenMetadataMerger.METADATA_SHA_NAME ) .toString() ) ); return result; } } return null; } /** * Generate maven-metadata.xml and checksum files. * @param group * @param members Concrete stores in group * @param path * @param eventMetadata * @return * @throws IndyWorkflowException */ @Override @Measure public Transfer generateGroupFileContent( final Group group, final List<ArtifactStore> members, final String path, final EventMetadata eventMetadata ) throws IndyWorkflowException { final Transfer rawTarget = fileManager.getTransfer( group, path ); // First we check the metadata and all of its siblings metadata files if ( canProcess( path ) && exists( rawTarget ) ) { // Means there is no metadata change if this transfer exists, so directly return it. logger.trace( "Raw metadata file exists for group {} of path {}, no need to regenerate.", group.getKey(), path ); eventMetadata.set( GROUP_METADATA_EXISTS, true ); return rawTarget; } // Then changed back to the metadata itself whatever the path is String toMergePath = path; if ( !path.endsWith( MavenMetadataMerger.METADATA_NAME ) ) { toMergePath = normalize( normalize( parentPath( toMergePath ) ), MavenMetadataMerger.METADATA_NAME ); } final Transfer target = fileManager.getTransfer( group, toMergePath ); if ( exists( target ) ) { // Means there is no metadata change if this transfer exists, so directly return it. logger.trace( "Merged metadata file exists for group {} of path {}, no need to regenerate.", group.getKey(), toMergePath ); eventMetadata.set( GROUP_METADATA_EXISTS, true ); return target; } AtomicReference<IndyWorkflowException> wfEx = new AtomicReference<>(); final String mergePath = toMergePath; boolean mergingDone = mergerLocks.ifUnlocked( computeKey(group, toMergePath), p->{ try { logger.debug( "Start metadata generation for metadata file {} in group {}", path, group ); List<StoreKey> contributing = new ArrayList<>(); final Metadata md = generateGroupMetadata( group, members, contributing, path ); if ( md != null ) { final Versioning versioning = md.getVersioning(); logger.trace( "Regenerated Metadata for group {} of path {}: latest version: {}, versions: {}", group.getKey(), mergePath, versioning != null ? versioning.getLatest() : null, versioning != null ? versioning.getVersions() : null ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { logger.trace( "Regenerate lost metadata, group: {}, path: {}", group.getKey(), path ); new MetadataXpp3Writer().write( baos, md ); final byte[] merged = baos.toByteArray(); try (final OutputStream fos = target.openOutputStream( TransferOperation.GENERATE, true, eventMetadata )) { fos.write( merged ); } catch ( final IOException e ) { throw new IndyWorkflowException( "Failed to write merged metadata to: {}.\nError: {}", e, target, e.getMessage() ); } String mergeInfo = writeGroupMergeInfo( md, group, contributing, mergePath ); eventMetadata.set( GROUP_METADATA_GENERATED, true ); MetadataInfo info = new MetadataInfo( md ); info.setMetadataMergeInfo( mergeInfo ); putToMetadataCache( group.getKey(), mergePath, info ); } catch ( final IOException e ) { logger.error( String.format( "Cannot write consolidated metadata: %s to: %s. Reason: %s", path, group.getKey(), e.getMessage() ), e ); } } } catch ( IndyWorkflowException e ) { wfEx.set( e ); return false; } return true; }, (p,mergerLock)->{ logger.info( "The metadata generation is still in process by another thread for the metadata file for this path {} in group {}, so block current thread to wait for result", path, group ); return mergerLocks.waitForLock( THREAD_WAITING_TIME_SECONDS, mergerLock ); } ); IndyWorkflowException ex = wfEx.get(); if ( ex != null ) { throw ex; } if ( exists( target ) ) { // if this is a checksum file, we need to return the original path (if it is metadata, original is target) Transfer original = fileManager.getTransfer( group, path ); if ( exists( original ) ) { if ( toMergePath != path ) { logger.debug( "This is a checksum file, return the original path {}", path ); } return original; } } if ( mergingDone ) { logger.info( "Merging finished but the merging file not created correctly. See merging related log for details. Merging group: {}, path: {}", group, path ); } else { logger.error( "Merging not finished but thread waiting timeout, caused current thread will get a null merging result. Try to enlarge the waiting timeout. Merging group: {}, path: {}", group, path ); } return null; } private String computeKey( final Group group, final String path ) { return group.getKey().toString() + "-" + path; } private String writeGroupMergeInfo( final Metadata md, final Group group, final List<StoreKey> contributingMembers, final String path ) throws IndyWorkflowException { logger.trace( "Start write .info file based on if the cache exists for group {} of members {} in path {}. ", group.getKey(), contributingMembers, path ); final Transfer mergeInfoTarget = fileManager.getTransfer( group, path + GroupMergeHelper.MERGEINFO_SUFFIX ); logger.trace( ".info file not found for {} of members {} in path {}", group.getKey(), contributingMembers, path ); logger.trace( "metadata merge info not cached for group {} of members {} in path {}, will regenerate.", group.getKey(), contributingMembers, path ); String metaMergeInfo = helper.generateMergeInfoFromKeys( contributingMembers ); logger.trace( "Metadata merge info for {} of members {} in path {} is {}", group.getKey(), contributingMembers, path, metaMergeInfo ); helper.writeMergeInfo( metaMergeInfo, group, path ); logger.trace( ".info file regenerated for group {} of members {} in path. Full path: {}", group.getKey(), contributingMembers, path ); return metaMergeInfo; } /** * Generate group related files (e.g maven-metadata.xml) from three levels. * 1. cache, which means all the generation of the files will be cached. In terms of cache clearing, see #{@link MetadataMergeListener} * 2. read cached from member hosted repos and try to download from member remote repos * 3. generate by member hosted repos (list dir trying to find version directories) * * @param group * @param members concrete store in group * @param path */ private Metadata generateGroupMetadata( final Group group, final List<ArtifactStore> members, final List<StoreKey> contributingMembers, final String path ) throws IndyWorkflowException { if ( !canProcess( path ) ) { logger.error( "The path is not a metadata file: {} ", path ); return null; } String toMergePath = path; if ( !path.endsWith( MavenMetadataMerger.METADATA_NAME ) ) { toMergePath = normalize( normalize( parentPath( toMergePath ) ), MavenMetadataMerger.METADATA_NAME ); } Metadata meta = getMetaFromCache( group.getKey(), toMergePath ); if ( meta != null ) { return meta; } Metadata master = new Metadata(); master.setVersioning( new Versioning() ); MetadataIncrementalResult incrementalResult = new MetadataIncrementalResult( new HashSet<>( members ), Collections.emptySet(), master ); incrementalResult = mergeMissing( group, incrementalResult, toMergePath, "cached", this::retrieveCached ); contributingMembers.addAll( incrementalResult.merged ); incrementalResult = mergeMissing( group, incrementalResult, toMergePath, "downloaded", this::downloadMissing ); contributingMembers.addAll( incrementalResult.merged ); incrementalResult = mergeMissing( group, incrementalResult, toMergePath, "generated", this::generateMissing ); contributingMembers.addAll( incrementalResult.merged ); if ( metadataProviders != null ) { master = mergeProviderMetadata( group, incrementalResult.result, toMergePath ); } else { master = incrementalResult.result; } if ( !incrementalResult.missing.isEmpty() ) { logger.warn( "After download and generation attempts, metadata is still missing from the following stores: {}, size: {}", incrementalResult.missing, incrementalResult.missing.size() ); } Versioning versioning = master.getVersioning(); List<String> versions = versioning.getVersions(); logger.debug( "Get versioning, versions: {}, release: {}, latest: {}", versions, versioning.getRelease(), versioning.getLatest() ); if ( versions != null && !versions.isEmpty() ) { merger.sortVersions( master ); return master; } List<SnapshotVersion> snapshotVersions = versioning.getSnapshotVersions(); if ( snapshotVersions != null && !snapshotVersions.isEmpty() ) { if ( logger.isTraceEnabled() ) { snapshotVersions.forEach( snapshotVersion -> logger.trace( "snapshotVersion: {}", snapshotVersion.getVersion() ) ); } return master; } List<Plugin> plugins = master.getPlugins(); if ( plugins != null && !plugins.isEmpty() ) { return master; } logger.info( "The group metadata generation is not successful for path: {} in group: {}", path, group ); return null; } private void putToMetadataCache( StoreKey key, String toMergePath, MetadataInfo meta ) { cacheManager.put( new MetadataKey( key, toMergePath ), meta ); } private Callable<MetadataResult> generateMissing( ArtifactStore store, String toMergePath ) { return ()->{ addFieldToActiveSpan( "storekey", store.getKey().toString() ); addFieldToActiveSpan( "path", toMergePath ); addFieldToActiveSpan( "activity", "generateMissing" ); try { logger.trace( "Starting metadata generation: {}:{}", store.getKey(), toMergePath ); Transfer memberMetaTxfr = generateFileContent( store, toMergePath, new EventMetadata() ); if ( exists( memberMetaTxfr ) ) { final MetadataXpp3Reader reader = new MetadataXpp3Reader(); try (InputStream in = memberMetaTxfr.openInputStream()) { String content = IOUtils.toString( in ); Metadata memberMeta = reader.read( new StringReader( content ), false ); clearObsoleteFiles( memberMetaTxfr ); return new MetadataResult( store, memberMeta ); } } } catch ( final Exception e ) { addFieldToActiveSpan( "error", e.getClass().getSimpleName() ); addFieldToActiveSpan( "error.message", e.getMessage() ); String msg = String.format( "EXCLUDING Failed generated metadata: %s:%s. Reason: %s", store.getKey(), toMergePath, e.getMessage() ); logger.error( msg, e ); } finally { logger.trace( "Ending metadata generation: {}:{}", store.getKey(), toMergePath ); } return new MetadataResult( store, null ); }; } /** * Clear obsolete files after a meta is generated. This may be http download metadata, etc. * @param item */ private void clearObsoleteFiles( Transfer item ) { Transfer httpMeta = item.getSiblingMeta( HTTP_METADATA_EXT ); try { httpMeta.delete(); } catch ( IOException e ) { logger.warn( "Failed to delete {}", httpMeta.getResource() ); } } private Callable<MetadataResult> retrieveCached( final ArtifactStore store, final String toMergePath ) { return ()->{ addFieldToActiveSpan( "storekey", store.getKey().toString() ); addFieldToActiveSpan( "path", toMergePath ); addFieldToActiveSpan( "activity", "retrieveCached" ); Metadata memberMeta; memberMeta = getMetaFromCache( store.getKey(), toMergePath ); if ( memberMeta != null ) { return new MetadataResult( store, memberMeta ); } return new MetadataResult( store, null ); }; } private static final class MetadataResult { private final ArtifactStore store; private final Metadata metadata; private final boolean missing; public MetadataResult( final ArtifactStore store, final Metadata metadata ) { this.store = store; this.metadata = metadata; this.missing = metadata == null; } } private static final class MetadataIncrementalResult { private final Set<ArtifactStore> missing; private final Set<StoreKey> merged; private final Metadata result; public MetadataIncrementalResult( final Set<ArtifactStore> missing, final Set<StoreKey> merged, final Metadata result ) { this.missing = missing; this.merged = merged; this.result = result; } } private MetadataIncrementalResult mergeMissing( final Group group, final MetadataIncrementalResult incrementalResult, final String toMergePath, String description, BiFunction<ArtifactStore, String, Callable<MetadataResult>> func ) throws IndyWorkflowException { Set<ArtifactStore> missing = incrementalResult.missing; Metadata master = incrementalResult.result; logger.debug( "Merge member metadata for {}, {}, missing: {}, size: {}", group.getKey(), description, missing, missing.size() ); DrainingExecutorCompletionService<MetadataResult> svc = new DrainingExecutorCompletionService<>( mavenMDGeneratorService ); detectOverloadVoid( () -> missing.forEach( store -> svc.submit( func.apply( store, toMergePath ) ) ) ); Set<ArtifactStore> resultingMissing = new HashSet<>(); // return stores failed download Set<StoreKey> included = new HashSet<>(); try { svc.drain( mr -> { if ( mr != null ) { if ( mr.missing ) { resultingMissing.add( mr.store ); } else { included.add( mr.store.getKey() ); merger.merge( master, mr.metadata, group, toMergePath ); putToMetadataCache( mr.store.getKey(), toMergePath, new MetadataInfo( mr.metadata ) ); } } } ); } catch ( InterruptedException e ) { logger.debug( "Interrupted while merging " + description + " member metadata." ); } catch ( ExecutionException e ) { throw new IndyWorkflowException( "Failed to merge downloaded " + description + " member metadata.", e ); } return new MetadataIncrementalResult( resultingMissing, included, master ); } private Metadata mergeProviderMetadata( final Group group, final Metadata master, final String toMergePath ) throws IndyWorkflowException { logger.debug( "Merge metadata for non-store providers in: {} on path: {}", group.getKey(), toMergePath ); DrainingExecutorCompletionService<Metadata> svc = new DrainingExecutorCompletionService<>( mavenMDGeneratorService ); detectOverloadVoid( () -> metadataProviders.forEach( provider -> svc.submit( ()->{ try { return provider.getMetadata( group.getKey(), toMergePath ); } catch ( IndyWorkflowException e ) { logger.error( String.format( "Cannot read metadata: %s from metadata provider: %s. Reason: %s", toMergePath, provider.getClass().getSimpleName(), e.getMessage() ), e ); } return null; }) ) ); try { svc.drain( metadata -> { if ( metadata != null ) { merger.merge( master, metadata, group, toMergePath ); } } ); } catch ( InterruptedException e ) { logger.debug( "Interrupted while merging provider member metadata." ); } catch ( ExecutionException e ) { throw new IndyWorkflowException( "Failed to merge provider member metadata.", e ); } return master; } private Callable<MetadataResult> downloadMissing( ArtifactStore store, String toMergePath ) { return () -> { addFieldToActiveSpan( "storekey", store.getKey().toString() ); addFieldToActiveSpan( "path", toMergePath ); addFieldToActiveSpan( "activity", "downloadMissing" ); try { logger.trace( "Starting metadata download: {}:{}", store.getKey(), toMergePath ); Transfer memberMetaTxfr = fileManager.retrieveRaw( store, toMergePath, new EventMetadata() ); if ( exists( memberMetaTxfr ) ) { final MetadataXpp3Reader reader = new MetadataXpp3Reader(); try (InputStream in = memberMetaTxfr.openInputStream()) { String content = IOUtils.toString( in ); Metadata memberMeta = reader.read( new StringReader( content ), false ); return new MetadataResult( store, memberMeta ); } } else { return new MetadataResult( store, null ); } } catch ( final Exception e ) { String msg = String.format( "EXCLUDING Failed metadata download: %s:%s. Reason: %s", store.getKey(), toMergePath, e.getMessage() ); logger.error( msg, e ); // errors.add( msg ); } finally { logger.trace( "Ending metadata download: {}:{}", store.getKey(), toMergePath ); } return null; }; } private boolean exists( final Transfer target ) { return target != null && target.exists(); } private Metadata getMetaFromCache( final StoreKey key, final String path ) { final MetadataInfo metaMergeInfo = getMetaInfoFromCache( key, path ); if ( metaMergeInfo != null ) { logger.trace( "FOUND metadata: {} in group: {} with merge info:\n\n{}\n\n", path, key, metaMergeInfo.getMetadataMergeInfo() ); return metaMergeInfo.getMetadata(); } return null; } private MetadataInfo getMetaInfoFromCache( final StoreKey key, final String path ) { return cacheManager.get( new MetadataKey( key, path ) ); } @Override public boolean canProcess( final String path ) { for ( final String filename : HANDLED_FILENAMES ) { if ( path.endsWith( filename ) ) { return true; } } return false; } @Override public List<StoreResource> generateGroupDirectoryContent( final Group group, final List<ArtifactStore> members, final String path, final EventMetadata eventMetadata ) throws IndyWorkflowException { return generateDirectoryContent( group, path, Collections.emptyList(), eventMetadata ); } @Override protected String getMergedMetadataName() { return MavenMetadataMerger.METADATA_NAME; } private boolean writeVersionMetadata( final List<StoreResource> firstLevelFiles, final ArtifactStore store, final String path, final EventMetadata eventMetadata ) throws IndyWorkflowException { ArtifactPathInfo samplePomInfo = null; logger.debug( "writeVersionMetadata, firstLevelFiles:{}, store:{}", firstLevelFiles, store.getKey() ); // first level will contain version directories...for each directory, we need to verify the presence of a .pom file before including // as a valid version final List<SingleVersion> versions = new ArrayList<>(); nextTopResource: for ( final StoreResource topResource : firstLevelFiles ) { final String topPath = topResource.getPath(); if ( topPath.endsWith( "/" ) ) { final List<StoreResource> secondLevelListing = fileManager.listRaw( store, topPath ); for ( final StoreResource fileResource : secondLevelListing ) { if ( fileResource.getPath() .endsWith( ".pom" ) ) { ArtifactPathInfo filePomInfo = ArtifactPathInfo.parse( fileResource.getPath() ); // check if the pom is valid for the path if ( filePomInfo != null ) { versions.add( VersionUtils.createSingleVersion( new File( topPath ).getName() ) ); if ( samplePomInfo == null ) { samplePomInfo = filePomInfo; } continue nextTopResource; } } } } } if ( versions.isEmpty() ) { logger.debug( "writeVersionMetadata, versions is empty, store:{}", store.getKey() ); return false; } logger.debug( "writeVersionMetadata, versions: {}, store:{}", versions, store.getKey() ); Collections.sort( versions ); final Transfer metadataFile = fileManager.getTransfer( store, path ); OutputStream stream = null; try { final Document doc = xml.newDocumentBuilder() .newDocument(); final Map<String, String> coordMap = new HashMap<>(); coordMap.put( ARTIFACT_ID, samplePomInfo == null ? null : samplePomInfo.getArtifactId() ); coordMap.put( GROUP_ID, samplePomInfo == null ? null : samplePomInfo.getGroupId() ); final String lastUpdated = generateUpdateTimestamp( getCurrentTimestamp() ); doc.appendChild( doc.createElementNS( doc.getNamespaceURI(), "metadata" ) ); xml.createElement( doc.getDocumentElement(), null, coordMap ); final Map<String, String> versioningMap = new HashMap<>(); versioningMap.put( LAST_UPDATED, lastUpdated ); final SingleVersion latest = versions.get( versions.size() - 1 ); versioningMap.put( LATEST, latest.renderStandard() ); SingleVersion release = null; for ( int i = versions.size() - 1; i >= 0; i-- ) { final SingleVersion r = versions.get( i ); if ( r.isRelease() ) { release = r; break; } } if ( release != null ) { versioningMap.put( RELEASE, release.renderStandard() ); } xml.createElement( doc, "versioning", versioningMap ); final Element versionsElem = xml.createElement( doc, "versioning/versions", Collections.emptyMap() ); for ( final SingleVersion version : versions ) { final Element vElem = doc.createElement( VERSION ); vElem.setTextContent( version.renderStandard() ); versionsElem.appendChild( vElem ); } final String xmlStr = xml.toXML( doc, true ); logger.debug( "writeVersionMetadata, xmlStr: {}", xmlStr ); stream = metadataFile.openOutputStream( TransferOperation.GENERATE, true, eventMetadata ); stream.write( xmlStr.getBytes( UTF_8 ) ); } catch ( final GalleyMavenXMLException e ) { throw new IndyWorkflowException( "Failed to generate maven metadata file: %s. Reason: %s", e, path, e.getMessage() ); } catch ( final IOException e ) { throw new IndyWorkflowException( "Failed to write generated maven metadata file: %s. Reason: %s", e, metadataFile, e.getMessage() ); } finally { closeQuietly( stream ); } logger.debug( "writeVersionMetadata, DONE, store: {}", store.getKey() ); return true; } /** * First level will contain files that have the timestamp-buildNumber version suffix, e.g., 'o11yphant-metrics-api-1.0-20200805.065728-1.pom' * we need to parse each this info and add them to snapshot versions. */ private boolean writeSnapshotMetadata( final ArtifactPathInfo info, final List<StoreResource> firstLevelFiles, final ArtifactStore store, final String path, final EventMetadata eventMetadata ) throws IndyWorkflowException { final Map<SnapshotPart, Set<ArtifactPathInfo>> infosBySnap = new HashMap<>(); for ( final StoreResource resource : firstLevelFiles ) { final ArtifactPathInfo resInfo = ArtifactPathInfo.parse( resource.getPath() ); if ( resInfo != null ) { final SnapshotPart snap = resInfo.getSnapshotInfo(); Set<ArtifactPathInfo> infos = infosBySnap.computeIfAbsent( snap, k -> new HashSet<>() ); infos.add( resInfo ); } } if ( infosBySnap.isEmpty() ) { return false; } final List<SnapshotPart> snaps = new ArrayList<>( infosBySnap.keySet() ); Collections.sort( snaps ); final Transfer metadataFile = fileManager.getTransfer( store, path ); OutputStream stream = null; try { final Document doc = xml.newDocumentBuilder() .newDocument(); final Map<String, String> coordMap = new HashMap<>(); coordMap.put( ARTIFACT_ID, info.getArtifactId() ); coordMap.put( GROUP_ID, info.getGroupId() ); coordMap.put( VERSION, info.getReleaseVersion() + LOCAL_SNAPSHOT_VERSION_PART ); doc.appendChild( doc.createElementNS( doc.getNamespaceURI(), "metadata" ) ); xml.createElement( doc.getDocumentElement(), null, coordMap ); // the last one is the most recent SnapshotPart snap = snaps.get( snaps.size() - 1 ); Map<String, String> snapMap = new HashMap<>(); if ( snap.isLocalSnapshot() ) { snapMap.put( LOCAL_COPY, Boolean.TRUE.toString() ); } else { snapMap.put( TIMESTAMP, SnapshotUtils.generateSnapshotTimestamp( snap.getTimestamp() ) ); snapMap.put( BUILD_NUMBER, Integer.toString( snap.getBuildNumber() ) ); } final Date currentTimestamp = getCurrentTimestamp(); final String lastUpdated = getUpdateTimestamp( snap, currentTimestamp ); xml.createElement( doc, "versioning", Collections.singletonMap( LAST_UPDATED, lastUpdated ) ); xml.createElement( doc, "versioning/snapshot", snapMap ); for ( SnapshotPart snap1 : snaps ) { final Set<ArtifactPathInfo> infos = infosBySnap.get( snap1 ); for ( final ArtifactPathInfo pathInfo : infos ) { snapMap = new HashMap<>(); final TypeAndClassifier tc = new SimpleTypeAndClassifier( pathInfo.getType(), pathInfo.getClassifier() ); final TypeMapping mapping = typeMapper.lookup( tc ); final String classifier = mapping == null ? pathInfo.getClassifier() : mapping.getClassifier(); if ( classifier != null && classifier.length() > 0 ) { snapMap.put( CLASSIFIER, classifier ); } snapMap.put( EXTENSION, mapping == null ? pathInfo.getType() : mapping.getExtension() ); snapMap.put( VALUE, pathInfo.getVersion() ); snapMap.put( UPDATED, getUpdateTimestamp( pathInfo.getSnapshotInfo(), currentTimestamp ) ); xml.createElement( doc, "versioning/snapshotVersions/snapshotVersion", snapMap ); } } final String xmlStr = xml.toXML( doc, true ); stream = metadataFile.openOutputStream( TransferOperation.GENERATE, true, eventMetadata ); stream.write( xmlStr.getBytes( UTF_8 ) ); } catch ( final GalleyMavenXMLException e ) { throw new IndyWorkflowException( "Failed to generate maven metadata file: %s. Reason: %s", e, path, e.getMessage() ); } catch ( final IOException e ) { throw new IndyWorkflowException( "Failed to write generated maven metadata file: %s. Reason: %s", e, metadataFile, e.getMessage() ); } finally { closeQuietly( stream ); } return true; } private String getUpdateTimestamp( SnapshotPart snapshot, Date currentTimestamp ) { Date timestamp = snapshot.getTimestamp(); if ( timestamp == null ) { timestamp = currentTimestamp; } return generateUpdateTimestamp( timestamp ); } // Parking this here, transplanted from ScheduleManager, because this is where it belongs. It might be // covered elsewhere, but in case it's not, we can use this as a reference... // public void updateSnapshotVersions( final StoreKey key, final String path ) // { // final ArtifactPathInfo pathInfo = ArtifactPathInfo.parse( path ); // if ( pathInfo == null ) // { // return; // } // // final ArtifactStore store; // try // { // store = dataManager.getArtifactStore( key ); // } // catch ( final IndyDataException e ) // { // logger.error( String.format( "Failed to update metadata after snapshot deletion. Reason: {}", // e.getMessage() ), e ); // return; // } // // if ( store == null ) // { // logger.error( "Failed to update metadata after snapshot deletion in: {}. Reason: Cannot find corresponding ArtifactStore", // key ); // return; // } // // final Transfer item = fileManager.getStorageReference( store, path ); // if ( item.getParent() == null || item.getParent() // .getParent() == null ) // { // return; // } // // final Transfer metadata = fileManager.getStorageReference( store, item.getParent() // .getParent() // .getPath(), "maven-metadata.xml" ); // // if ( metadata.exists() ) // { // // logger.info( "[UPDATE VERSIONS] Updating snapshot versions for path: {} in store: {}", path, key.getName() ); // Reader reader = null; // Writer writer = null; // try // { // reader = new InputStreamReader( metadata.openInputStream() ); // final Metadata md = new MetadataXpp3Reader().read( reader ); // // final Versioning versioning = md.getVersioning(); // final List<String> versions = versioning.getVersions(); // // final String version = pathInfo.getVersion(); // String replacement = null; // // final int idx = versions.indexOf( version ); // if ( idx > -1 ) // { // if ( idx > 0 ) // { // replacement = versions.get( idx - 1 ); // } // // versions.remove( idx ); // } // // if ( version.equals( md.getVersion() ) ) // { // md.setVersion( replacement ); // } // // if ( version.equals( versioning.getLatest() ) ) // { // versioning.setLatest( replacement ); // } // // final SnapshotPart si = pathInfo.getSnapshotInfo(); // if ( si != null ) // { // final SnapshotPart siRepl = SnapshotUtils.extractSnapshotVersionPart( replacement ); // final Snapshot snapshot = versioning.getSnapshot(); // // final String siTstamp = SnapshotUtils.generateSnapshotTimestamp( si.getTimestamp() ); // if ( si.isRemoteSnapshot() && siTstamp.equals( snapshot.getTimestamp() ) // && si.getBuildNumber() == snapshot.getBuildNumber() ) // { // if ( siRepl != null ) // { // if ( siRepl.isRemoteSnapshot() ) // { // snapshot.setTimestamp( SnapshotUtils.generateSnapshotTimestamp( siRepl.getTimestamp() ) ); // snapshot.setBuildNumber( siRepl.getBuildNumber() ); // } // else // { // snapshot.setLocalCopy( true ); // } // } // else // { // versioning.setSnapshot( null ); // } // } // } // // writer = new OutputStreamWriter( metadata.openOutputStream( TransferOperation.GENERATE, true ) ); // new MetadataXpp3Writer().write( writer, md ); // } // catch ( final IOException e ) // { // logger.error( "Failed to update metadata after snapshot deletion.\n Snapshot: {}\n Metadata: {}\n Reason: {}", // e, item.getFullPath(), metadata, e.getMessage() ); // } // catch ( final XmlPullParserException e ) // { // logger.error( "Failed to update metadata after snapshot deletion.\n Snapshot: {}\n Metadata: {}\n Reason: {}", // e, item.getFullPath(), metadata, e.getMessage() ); // } // finally // { // closeQuietly( reader ); // closeQuietly( writer ); // } // } // } // }
package org.jgroups.demos; import org.jgroups.*; import org.jgroups.jmx.JmxConfigurator; import org.jgroups.stack.AddressGenerator; import org.jgroups.util.OneTimeAddressGenerator; import org.jgroups.util.Util; import javax.management.MBeanServer; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.List; /** * Shared whiteboard, each new instance joins the same group. Each instance chooses a random color, * mouse moves are broadcast to all group members, which then apply them to their canvas<p> * @author Bela Ban, Oct 17 2001 */ public class Draw extends ReceiverAdapter implements ActionListener, ChannelListener { protected String cluster_name="draw"; private JChannel channel=null; private int member_size=1; private JFrame mainFrame=null; private JPanel sub_panel=null; private DrawPanel panel=null; private JButton clear_button, leave_button; private final Random random=new Random(System.currentTimeMillis()); private final Font default_font=new Font("Helvetica",Font.PLAIN,12); private final Color draw_color=selectColor(); private static final Color background_color=Color.white; boolean no_channel=false; boolean jmx; private boolean use_state=false; private long state_timeout=5000; private boolean use_unicasts=false; protected boolean send_own_state_on_merge=true; private final List<Address> members=new ArrayList<>(); public Draw(String props, boolean no_channel, boolean jmx, boolean use_state, long state_timeout, boolean use_unicasts, String name, boolean send_own_state_on_merge, AddressGenerator gen) throws Exception { this.no_channel=no_channel; this.jmx=jmx; this.use_state=use_state; this.state_timeout=state_timeout; this.use_unicasts=use_unicasts; if(no_channel) return; channel=new JChannel(props).addAddressGenerator(gen).setName(name); channel.setReceiver(this).addChannelListener(this); this.send_own_state_on_merge=send_own_state_on_merge; } public Draw(JChannel channel) throws Exception { this.channel=channel; channel.setReceiver(this); channel.addChannelListener(this); } public Draw(JChannel channel, boolean use_state, long state_timeout) throws Exception { this.channel=channel; channel.setReceiver(this); channel.addChannelListener(this); this.use_state=use_state; this.state_timeout=state_timeout; } public String getClusterName() { return cluster_name; } public void setClusterName(String clustername) { if(clustername != null) this.cluster_name=clustername; } public static void main(String[] args) { Draw draw=null; String props=null; boolean no_channel=false; boolean jmx=true; boolean use_state=false; String group_name=null; long state_timeout=5000; boolean use_unicasts=false; String name=null; boolean send_own_state_on_merge=true; AddressGenerator generator=null; for(int i=0; i < args.length; i++) { if("-help".equals(args[i])) { help(); return; } if("-props".equals(args[i])) { props=args[++i]; continue; } if("-no_channel".equals(args[i])) { no_channel=true; continue; } if("-jmx".equals(args[i])) { jmx=Boolean.parseBoolean(args[++i]); continue; } if("-clustername".equals(args[i])) { group_name=args[++i]; continue; } if("-state".equals(args[i])) { use_state=true; continue; } if("-timeout".equals(args[i])) { state_timeout=Long.parseLong(args[++i]); continue; } if("-use_unicasts".equals(args[i])) { use_unicasts=true; continue; } if("-name".equals(args[i])) { name=args[++i]; continue; } if("-send_own_state_on_merge".equals(args[i])) { send_own_state_on_merge=Boolean.getBoolean(args[++i]); continue; } if("-uuid".equals(args[i])) { generator=new OneTimeAddressGenerator(Long.valueOf(args[++i])); continue; } help(); return; } try { draw=new Draw(props, no_channel, jmx, use_state, state_timeout, use_unicasts, name, send_own_state_on_merge, generator); if(group_name != null) draw.setClusterName(group_name); draw.go(); } catch(Throwable e) { e.printStackTrace(System.err); System.exit(0); } } static void help() { System.out.println("\nDraw [-help] [-no_channel] [-props <protocol stack definition>]" + " [-clustername <name>] [-state] [-timeout <state timeout>] [-use_unicasts] " + "[-jmx <true | false>] [-name <logical name>] [-send_own_state_on_merge true|false] " + "[-uuid <UUID>]"); System.out.println("-no_channel: doesn't use JGroups at all, any drawing will be relected on the " + "whiteboard directly"); System.out.println("-props: argument can be an old-style protocol stack specification, or it can be " + "a URL. In the latter case, the protocol specification will be read from the URL\n"); } private Color selectColor() { int red=Math.abs(random.nextInt() % 255); int green=Math.abs(random.nextInt() % 255); int blue=Math.abs(random.nextInt() % 255); return new Color(red, green, blue); } private void sendToAll(byte[] buf) throws Exception { for(Address mbr: members) channel.send(new Message(mbr, buf)); } public void go() throws Exception { if(!no_channel && !use_state) channel.connect(cluster_name); mainFrame=new JFrame(); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); panel=new DrawPanel(use_state); panel.setBackground(background_color); sub_panel=new JPanel(); mainFrame.getContentPane().add("Center", panel); clear_button=new JButton("Clear"); clear_button.setFont(default_font); clear_button.addActionListener(this); leave_button=new JButton("Leave"); leave_button.setFont(default_font); leave_button.addActionListener(this); sub_panel.add("South", clear_button); sub_panel.add("South", leave_button); mainFrame.getContentPane().add("South", sub_panel); mainFrame.setBackground(background_color); clear_button.setForeground(Color.blue); leave_button.setForeground(Color.blue); mainFrame.pack(); mainFrame.setLocation(15, 25); mainFrame.setBounds(new Rectangle(250, 250)); if(!no_channel && use_state) { channel.connect(cluster_name, null, state_timeout); } mainFrame.setVisible(true); setTitle(); } void setTitle(String title) { String tmp=""; if(no_channel) { mainFrame.setTitle(" Draw Demo "); return; } if(title != null) { mainFrame.setTitle(title); } else { if(channel.getAddress() != null) tmp+=channel.getAddress(); tmp+=" (" + member_size + ")"; mainFrame.setTitle(tmp); } } void setTitle() { setTitle(null); } public void receive(Message msg) { byte[] buf=msg.getRawBuffer(); if(buf == null) { System.err.printf("%s: received null buffer from %s, headers: %s\n", channel.getAddress(), msg.src(), msg.printHeaders()); return; } try { DrawCommand comm=Util.streamableFromByteBuffer(DrawCommand::new, buf, msg.getOffset(), msg.getLength()); switch(comm.mode) { case DrawCommand.DRAW: if(panel != null) panel.drawPoint(comm); break; case DrawCommand.CLEAR: clearPanel(); break; default: System.err.println("***** received invalid draw command " + comm.mode); break; } } catch(Exception e) { e.printStackTrace(); } } public void viewAccepted(View v) { member_size=v.size(); if(mainFrame != null) setTitle(); members.clear(); members.addAll(v.getMembers()); if(v instanceof MergeView) { System.out.println("** " + v); // This is an example of a simple merge function, which fetches the state from the coordinator // on a merge and overwrites all of its own state if(use_state && !members.isEmpty()) { Address coord=members.get(0); Address local_addr=channel.getAddress(); if(local_addr != null && !local_addr.equals(coord)) { try { // make a copy of our state first Map<Point,Color> copy=null; if(send_own_state_on_merge) { synchronized(panel.state) { copy=new LinkedHashMap<>(panel.state); } } System.out.println("fetching state from " + coord); channel.getState(coord, 5000); if(copy != null) sendOwnState(copy); // multicast my own state so everybody else has it too } catch(Exception e) { e.printStackTrace(); } } } } else System.out.println("** View=" + v); } public void getState(OutputStream ostream) throws Exception { panel.writeState(ostream); } public void setState(InputStream istream) throws Exception { panel.readState(istream); } /* --------------- Callbacks --------------- */ public void clearPanel() { if(panel != null) panel.clear(); } public void sendClearPanelMsg() { DrawCommand comm=new DrawCommand(DrawCommand.CLEAR); try { byte[] buf=Util.streamableToByteBuffer(comm); if(use_unicasts) sendToAll(buf); else channel.send(new Message(null, buf)); } catch(Exception ex) { System.err.println(ex); } } public void actionPerformed(ActionEvent e) { String command=e.getActionCommand(); switch(command) { case "Clear": if(no_channel) { clearPanel(); return; } sendClearPanelMsg(); break; case "Leave": stop(); break; default: System.out.println("Unknown action"); break; } } public void stop() { if(!no_channel) { try { channel.close(); } catch(Exception ex) { System.err.println(ex); } } mainFrame.setVisible(false); mainFrame.dispose(); } protected void sendOwnState(final Map<Point,Color> copy) { if(copy == null) return; for(Point point: copy.keySet()) { // we don't need the color: it is our draw_color anyway DrawCommand comm=new DrawCommand(DrawCommand.DRAW, point.x, point.y, draw_color.getRGB()); try { byte[] buf=Util.streamableToByteBuffer(comm); if(use_unicasts) sendToAll(buf); else channel.send(new Message(null, buf)); } catch(Exception ex) { System.err.println(ex); } } } /* ------------------------------ ChannelListener interface -------------------------- */ public void channelConnected(JChannel channel) { if(jmx) { Util.registerChannel(channel, "jgroups"); } } public void channelDisconnected(JChannel channel) { if(jmx) { MBeanServer server=Util.getMBeanServer(); if(server != null) { try { JmxConfigurator.unregisterChannel(channel, server, cluster_name); } catch(Exception e) { e.printStackTrace(); } } } } public void channelClosed(JChannel channel) { } /* --------------------------- End of ChannelListener interface ---------------------- */ protected class DrawPanel extends JPanel implements MouseMotionListener { protected final Dimension preferred_size=new Dimension(235, 170); protected Image img; // for drawing pixels protected Dimension d, imgsize; protected Graphics gr; protected final Map<Point,Color> state; public DrawPanel(boolean use_state) { if(use_state) state=new LinkedHashMap<>(); else state=null; createOffscreenImage(false); addMouseMotionListener(this); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { if(getWidth() <= 0 || getHeight() <= 0) return; createOffscreenImage(false); } }); } public void writeState(OutputStream outstream) throws IOException { if(state == null) return; synchronized(state) { DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(outstream)); // DataOutputStream dos=new DataOutputStream(outstream); dos.writeInt(state.size()); for(Map.Entry<Point,Color> entry: state.entrySet()) { Point point=entry.getKey(); Color col=entry.getValue(); dos.writeInt(point.x); dos.writeInt(point.y); dos.writeInt(col.getRGB()); } dos.flush(); System.out.println("wrote " + state.size() + " elements"); } } public void readState(InputStream instream) throws IOException { DataInputStream in=new DataInputStream(new BufferedInputStream(instream)); Map<Point,Color> new_state=new LinkedHashMap<>(); int num=in.readInt(); for(int i=0; i < num; i++) { Point point=new Point(in.readInt(), in.readInt()); Color col=new Color(in.readInt()); new_state.put(point, col); } synchronized(state) { state.clear(); state.putAll(new_state); System.out.println("read " + state.size() + " elements"); createOffscreenImage(true); } } void createOffscreenImage(boolean discard_image) { d=getSize(); if(discard_image) { img=null; imgsize=null; } if(img == null || imgsize == null || imgsize.width != d.width || imgsize.height != d.height) { img=createImage(d.width, d.height); if(img != null) { gr=img.getGraphics(); if(gr != null && state != null) { drawState(); } } imgsize=d; } repaint(); } /* ---------------------- MouseMotionListener interface------------------------- */ public void mouseMoved(MouseEvent e) {} public void mouseDragged(MouseEvent e) { int x=e.getX(), y=e.getY(); DrawCommand comm=new DrawCommand(DrawCommand.DRAW, x, y, draw_color.getRGB()); if(no_channel) { drawPoint(comm); return; } try { byte[] buf=Util.streamableToByteBuffer(comm); if(use_unicasts) sendToAll(buf); else channel.send(new Message(null, buf)); } catch(Exception ex) { System.err.println(ex); } } /* ------------------- End of MouseMotionListener interface --------------------- */ /** * Adds pixel to queue and calls repaint() whenever we have MAX_ITEMS pixels in the queue * or when MAX_TIME msecs have elapsed (whichever comes first). The advantage compared to just calling * repaint() after adding a pixel to the queue is that repaint() can most often draw multiple points * at the same time. */ public void drawPoint(DrawCommand c) { if(c == null || gr == null) return; Color col=new Color(c.rgb); gr.setColor(col); gr.fillOval(c.x, c.y, 10, 10); repaint(); if(state != null) { synchronized(state) { state.put(new Point(c.x, c.y), col); } } } public void clear() { if(gr == null) return; gr.clearRect(0, 0, getSize().width, getSize().height); repaint(); if(state != null) { synchronized(state) { state.clear(); } } } /** Draw the entire panel from the state */ public void drawState() { // clear(); Map.Entry entry; Point pt; Color col; synchronized(state) { for(Iterator it=state.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); pt=(Point)entry.getKey(); col=(Color)entry.getValue(); gr.setColor(col); gr.fillOval(pt.x, pt.y, 10, 10); } } repaint(); } public Dimension getPreferredSize() { return preferred_size; } public void paintComponent(Graphics g) { super.paintComponent(g); if(img != null) { g.drawImage(img, 0, 0, null); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ivy.osgi.repo; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; 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.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.ivy.core.IvyPatternHelper; import org.apache.ivy.core.module.descriptor.Artifact; import org.apache.ivy.core.module.descriptor.Configuration; import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor; import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor; import org.apache.ivy.core.module.descriptor.DependencyDescriptor; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.apache.ivy.core.report.DownloadStatus; import org.apache.ivy.core.report.MetadataArtifactDownloadReport; import org.apache.ivy.core.resolve.IvyNode; import org.apache.ivy.core.resolve.ResolveData; import org.apache.ivy.core.resolve.ResolvedModuleRevision; import org.apache.ivy.osgi.core.BundleInfo; import org.apache.ivy.osgi.core.BundleInfoAdapter; import org.apache.ivy.osgi.util.Version; import org.apache.ivy.plugins.repository.Resource; import org.apache.ivy.plugins.repository.url.URLRepository; import org.apache.ivy.plugins.repository.url.URLResource; import org.apache.ivy.plugins.resolver.BasicResolver; import org.apache.ivy.plugins.resolver.util.MDResolvedResource; import org.apache.ivy.plugins.resolver.util.ResolvedResource; import org.apache.ivy.plugins.resolver.util.ResourceMDParser; import org.apache.ivy.util.Message; public abstract class AbstractOSGiResolver extends BasicResolver { private static final String CAPABILITY_EXTRA_ATTR = "osgi_bundle"; private RepoDescriptor repoDescriptor = null; private URLRepository repository = new URLRepository(); public static class RequirementStrategy { // take the first matching public static RequirementStrategy first = new RequirementStrategy(); // if there are any ambiguity, fail to resolve public static RequirementStrategy noambiguity = new RequirementStrategy(); public static RequirementStrategy valueOf(String strategy) { if (strategy.equals("first")) { return first; } if (strategy.equals("noambiguity")) { return noambiguity; } throw new IllegalStateException(); } } private RequirementStrategy requirementStrategy = RequirementStrategy.noambiguity; public void setRequirementStrategy(RequirementStrategy importPackageStrategy) { this.requirementStrategy = importPackageStrategy; } public void setRequirementStrategy(String strategy) { setRequirementStrategy(RequirementStrategy.valueOf(strategy)); } protected void setRepoDescriptor(RepoDescriptor repoDescriptor) { this.repoDescriptor = repoDescriptor; } public URLRepository getRepository() { return repository; } protected void ensureInit() { if (repoDescriptor == null) { init(); } } abstract protected void init(); private RepoDescriptor getRepoDescriptor() { ensureInit(); return repoDescriptor; } public boolean isAllownomd() { // this a repo based resolver, we always have md return false; } public ResolvedResource findIvyFileRef(DependencyDescriptor dd, ResolveData data) { ModuleRevisionId mrid = dd.getDependencyRevisionId(); String osgiType = mrid.getOrganisation(); if (osgiType == null) { throw new RuntimeException("Unsupported OSGi module Id: " + mrid.getModuleId()); } String id = mrid.getName(); Set/* <ModuleDescriptor> */mds = getRepoDescriptor().findModule(osgiType, id); if (mds == null || mds.isEmpty()) { Message.verbose("\t " + id + " not found."); return null; } ResolvedResource[] ret; if (BundleInfo.BUNDLE_TYPE.equals(osgiType)) { ret = findBundle(dd, data, mds); } else { ret = findCapability(dd, data, mds); } ResolvedResource found = findResource(ret, getDefaultRMDParser(dd.getDependencyId()), mrid, data.getDate()); if (found == null) { Message.debug("\t" + getName() + ": no resource found for " + mrid); } return found; } public ResolvedResource[] findBundle(DependencyDescriptor dd, ResolveData data, Set/* * < * ModuleDescriptor * > */mds) { ResolvedResource[] ret = new ResolvedResource[mds.size()]; int i = 0; Iterator itMd = mds.iterator(); while (itMd.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itMd.next(); MetadataArtifactDownloadReport report = new MetadataArtifactDownloadReport(null); report.setDownloadStatus(DownloadStatus.NO); report.setSearched(true); ResolvedModuleRevision rmr = new ResolvedModuleRevision(this, this, md, report); MDResolvedResource mdrr = new MDResolvedResource(null, md.getRevision(), rmr); ret[i++] = mdrr; } return ret; } public ResolvedResource[] findCapability(DependencyDescriptor dd, ResolveData data, Set/* * < * ModuleDescriptor * > */mds) { ResolvedResource[] ret = new ResolvedResource[mds.size()]; int i = 0; Iterator itMd = mds.iterator(); while (itMd.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itMd.next(); IvyNode node = data.getNode(md.getModuleRevisionId()); if (node != null && node.getDescriptor() != null) { // already resolved import, no need to go further return new ResolvedResource[] {buildResolvedCapabilityMd(dd, node.getDescriptor())}; } ret[i++] = buildResolvedCapabilityMd(dd, md); } return ret; } private MDResolvedResource buildResolvedCapabilityMd(DependencyDescriptor dd, ModuleDescriptor md) { String org = dd.getDependencyRevisionId().getOrganisation(); String name = dd.getDependencyRevisionId().getName(); String rev = (String) md.getExtraInfo().get( BundleInfoAdapter.EXTRA_INFO_EXPORT_PREFIX + name); ModuleRevisionId capabilityRev = ModuleRevisionId.newInstance(org, name, rev, Collections.singletonMap(CAPABILITY_EXTRA_ATTR, md.getModuleRevisionId().toString())); DefaultModuleDescriptor capabilityMd = new DefaultModuleDescriptor(capabilityRev, "release", new Date()); String useConf = BundleInfoAdapter.CONF_USE_PREFIX + dd.getDependencyRevisionId().getName(); capabilityMd.addConfiguration(BundleInfoAdapter.CONF_DEFAULT); capabilityMd.addConfiguration(BundleInfoAdapter.CONF_OPTIONAL); capabilityMd.addConfiguration(BundleInfoAdapter.CONF_TRANSITIVE_OPTIONAL); capabilityMd.addConfiguration(new Configuration(useConf)); DefaultDependencyDescriptor capabilityDD = new DefaultDependencyDescriptor( md.getModuleRevisionId(), false); capabilityDD.addDependencyConfiguration(BundleInfoAdapter.CONF_NAME_DEFAULT, BundleInfoAdapter.CONF_NAME_DEFAULT); capabilityDD.addDependencyConfiguration(BundleInfoAdapter.CONF_NAME_OPTIONAL, BundleInfoAdapter.CONF_NAME_OPTIONAL); capabilityDD.addDependencyConfiguration(BundleInfoAdapter.CONF_NAME_TRANSITIVE_OPTIONAL, BundleInfoAdapter.CONF_NAME_TRANSITIVE_OPTIONAL); capabilityDD.addDependencyConfiguration(useConf, useConf); capabilityMd.addDependency(capabilityDD); MetadataArtifactDownloadReport report = new MetadataArtifactDownloadReport(null); report.setDownloadStatus(DownloadStatus.NO); report.setSearched(true); ResolvedModuleRevision rmr = new ResolvedModuleRevision(this, this, capabilityMd, report); return new MDResolvedResource(null, capabilityMd.getRevision(), rmr); } public ResolvedResource findResource(ResolvedResource[] rress, ResourceMDParser rmdparser, ModuleRevisionId mrid, Date date) { ResolvedResource found = super.findResource(rress, rmdparser, mrid, date); String osgiType = mrid.getOrganisation(); // for non bundle requirement : log the selected bundle if (!BundleInfo.BUNDLE_TYPE.equals(osgiType)) { // several candidates with different symbolic name : make an warning about the ambiguity if (rress.length != 1) { // several candidates with different symbolic name ? Map/* <String, List<MDResolvedResource>> */matching = new HashMap(); for (int i = 0; i < rress.length; i++) { String name = ((MDResolvedResource) rress[i]).getResolvedModuleRevision() .getDescriptor().getExtraAttribute(CAPABILITY_EXTRA_ATTR); List/* <MDResolvedResource> */list = (List) matching.get(name); if (list == null) { list = new ArrayList/* <MDResolvedResource> */(); matching.put(name, list); } list.add(rress[i]); } if (matching.keySet().size() != 1) { if (requirementStrategy == RequirementStrategy.first) { Message.warn("Ambiguity for the '" + osgiType + "' requirement " + mrid.getName() + ";version=" + mrid.getRevision()); Iterator itMatching = matching.entrySet().iterator(); while (itMatching.hasNext()) { Entry/* <String, List<MDResolvedResource>> */entry = (Entry) itMatching .next(); Message.warn("\t" + entry.getKey()); Iterator itB = ((List) entry.getValue()).iterator(); while (itB.hasNext()) { MDResolvedResource c = (MDResolvedResource) itB.next(); Message.warn("\t\t" + c.getRevision() + (found == c ? " (selected)" : "")); } } } else if (requirementStrategy == RequirementStrategy.noambiguity) { Message.error("Ambiguity for the '" + osgiType + "' requirement " + mrid.getName() + ";version=" + mrid.getRevision()); Iterator itMatching = matching.entrySet().iterator(); while (itMatching.hasNext()) { Entry/* <String, List<MDResolvedResource>> */entry = (Entry) itMatching .next(); Message.error("\t" + entry.getKey()); Iterator itB = ((List) entry.getValue()).iterator(); while (itB.hasNext()) { MDResolvedResource c = (MDResolvedResource) itB.next(); Message.error("\t\t" + c.getRevision() + (found == c ? " (best match)" : "")); } } return null; } } } Message.info("'" + osgiType + "' requirement " + mrid.getName() + ";version=" + mrid.getRevision() + " satisfied by " + ((MDResolvedResource) found).getResolvedModuleRevision().getId().getName() + ";" + found.getRevision()); } return found; } public ResolvedResource findArtifactRef(Artifact artifact, Date date) { URL url = artifact.getUrl(); if (url == null) { // not an artifact resolved by this resolver return null; } Message.verbose("\tusing url for " + artifact + ": " + url); logArtifactAttempt(artifact, url.toExternalForm()); Resource resource = new URLResource(url); return new ResolvedResource(resource, artifact.getModuleRevisionId().getRevision()); } protected void checkModuleDescriptorRevision(ModuleDescriptor systemMd, ModuleRevisionId systemMrid) { String osgiType = systemMrid.getOrganisation(); // only check revision if we're searching for a bundle (package and bundle have different // version if (osgiType == null || osgiType.equals(BundleInfo.BUNDLE_TYPE)) { super.checkModuleDescriptorRevision(systemMd, systemMrid); } } protected Collection/* <String> */filterNames(Collection/* <String> */names) { getSettings().filterIgnore(names); return names; } protected Collection findNames(Map tokenValues, String token) { if (IvyPatternHelper.ORGANISATION_KEY.equals(token)) { return getRepoDescriptor().getModuleByCapbilities().keySet(); } String osgiType = (String) tokenValues.get(IvyPatternHelper.ORGANISATION_KEY); if (osgiType == null || osgiType.length() == 0) { return Collections.EMPTY_LIST; } String rev = (String) tokenValues.get(IvyPatternHelper.REVISION_KEY); if (IvyPatternHelper.MODULE_KEY.equals(token)) { Map/* <String, Map<String, Set<ModuleDescriptor>>> */moduleByCapbilities = getRepoDescriptor() .getModuleByCapbilities(); if (osgiType != null) { Map/* <String, Set<ModuleDescriptor>> */moduleByCapabilityValue = (Map) moduleByCapbilities .get(osgiType); if (moduleByCapabilityValue == null) { return Collections.EMPTY_LIST; } Set/* <String> */capabilityValues = new HashSet(); return moduleByCapabilityValue.keySet(); } else { Set/* <String> */capabilityValues = new HashSet(); Iterator/* <Map<String, Set<ModuleDescriptor>>> */it = ((Collection) moduleByCapbilities .values()).iterator(); while (it.hasNext()) { Map/* <String, Set<ModuleDescriptor>> */moduleByCapbilityValue = (Map) it .next(); filterCapabilityValues(capabilityValues, moduleByCapbilityValue, tokenValues, rev); } return capabilityValues; } } if (IvyPatternHelper.REVISION_KEY.equals(token)) { String name = (String) tokenValues.get(IvyPatternHelper.MODULE_KEY); List/* <String> */versions = new ArrayList/* <String> */(); Set/* <ModuleDescriptor> */mds = getRepoDescriptor().findModule(osgiType, name); if (mds != null) { Iterator itMd = mds.iterator(); while (itMd.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itMd.next(); versions.add(md.getRevision()); } } return versions; } if (IvyPatternHelper.CONF_KEY.equals(token)) { String name = (String) tokenValues.get(IvyPatternHelper.MODULE_KEY); if (name == null) { return Collections.EMPTY_LIST; } if (osgiType.equals(BundleInfo.PACKAGE_TYPE)) { return Collections.singletonList(BundleInfoAdapter.CONF_USE_PREFIX + name); } Set/* <BundleCapabilityAndLocation> */bundleCapabilities = getRepoDescriptor() .findModule(osgiType, name); if (bundleCapabilities == null) { return Collections.EMPTY_LIST; } String version = (String) tokenValues.get(IvyPatternHelper.REVISION_KEY); if (version == null) { return Collections.EMPTY_LIST; } Version v; try { v = new Version(version); } catch (ParseException e) { return Collections.EMPTY_LIST; } BundleCapabilityAndLocation found = null; Iterator itBundle = bundleCapabilities.iterator(); while (itBundle.hasNext()) { BundleCapabilityAndLocation bundleCapability = (BundleCapabilityAndLocation) itBundle .next(); if (bundleCapability.getVersion().equals(v)) { found = bundleCapability; } } if (found == null) { return Collections.EMPTY_LIST; } List/* <String> */confs = BundleInfoAdapter.getConfigurations(found.getBundleInfo()); return confs; } return Collections.EMPTY_LIST; } /** * Populate capabilityValues with capability values for which at least one module match the * expected revision */ private void filterCapabilityValues(Set/* <String> */capabilityValues, Map/* <String, Set<ModuleDescriptor>> */moduleByCapbilityValue, Map/* <String, String */tokenValues, String rev) { if (rev == null) { // no revision, all match then capabilityValues.addAll(moduleByCapbilityValue.keySet()); } else { Iterator/* <Entry<String, Set<ModuleDescriptor>>> */it = moduleByCapbilityValue .entrySet().iterator(); while (it.hasNext()) { Entry/* <String, Set<ModuleDescriptor>> */entry = (Entry) it.next(); Iterator/* <ModuleDescriptor> */itModules = ((Set) entry.getValue()).iterator(); boolean moduleMatchRev = false; while (!moduleMatchRev && itModules.hasNext()) { ModuleDescriptor md = (ModuleDescriptor) itModules.next(); moduleMatchRev = rev.equals(md.getRevision()); } if (moduleMatchRev) { // at least one module matched, the capability value is ok to add capabilityValues.add(entry.getKey()); } } } } public Map[] listTokenValues(String[] tokens, Map criteria) { Set/* <String> */tokenSet = new HashSet/* <String> */(Arrays.asList(tokens)); Set/* <Map<String, String>> */listTokenValues = listTokenValues(tokenSet, criteria); return (Map[]) listTokenValues.toArray(new Map[listTokenValues.size()]); } private Set/* <Map<String, String>> */listTokenValues(Set/* <String> */tokens, Map/* * <String, * String> */criteria) { if (tokens.isEmpty()) { return Collections./* <Map<String, String>> */singleton(criteria); } Set/* <String> */tokenSet = new HashSet/* <String> */(tokens); Map/* <String, String> */values = new HashMap/* <String, String> */(); tokenSet.remove(IvyPatternHelper.ORGANISATION_KEY); String osgiType = (String) criteria.get(IvyPatternHelper.ORGANISATION_KEY); if (osgiType == null || osgiType.length() == 0) { return Collections.EMPTY_SET; } values.put(IvyPatternHelper.ORGANISATION_KEY, osgiType); if (osgiType == null) { Set/* <Map<String, String>> */tokenValues = new HashSet/* <Map<String, String>> */(); Map/* <String, String> */newCriteria = new HashMap/* <String, String> */(criteria); newCriteria.put(IvyPatternHelper.ORGANISATION_KEY, BundleInfo.BUNDLE_TYPE); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); newCriteria = new HashMap/* <String, String> */(criteria); newCriteria.put(IvyPatternHelper.ORGANISATION_KEY, BundleInfo.PACKAGE_TYPE); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); newCriteria = new HashMap/* <String, String> */(criteria); newCriteria.put(IvyPatternHelper.ORGANISATION_KEY, BundleInfo.SERVICE_TYPE); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); return tokenValues; } Set/* <String> */capabilities = getRepoDescriptor().getCapabilityValues(osgiType); if (capabilities == null || capabilities.isEmpty()) { return Collections.EMPTY_SET; } tokenSet.remove(IvyPatternHelper.MODULE_KEY); String module = (String) criteria.get(IvyPatternHelper.MODULE_KEY); if (module == null) { Set/* <Map<String, String>> */tokenValues = new HashSet/* <Map<String, String>> */(); Iterator itNames = capabilities.iterator(); while (itNames.hasNext()) { String name = (String) itNames.next(); Map/* <String, String> */newCriteria = new HashMap/* <String, String> */(criteria); newCriteria.put(IvyPatternHelper.MODULE_KEY, name); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); } return tokenValues; } values.put(IvyPatternHelper.MODULE_KEY, module); tokenSet.remove(IvyPatternHelper.REVISION_KEY); String rev = (String) criteria.get(IvyPatternHelper.REVISION_KEY); if (rev == null) { Set/* <BundleCapabilityAndLocation> */bundleCapabilities = getRepoDescriptor() .findModule(osgiType, module); if (bundleCapabilities == null) { return Collections.EMPTY_SET; } Set/* <Map<String, String>> */tokenValues = new HashSet/* <Map<String, String>> */(); Iterator itBundle = bundleCapabilities.iterator(); while (itBundle.hasNext()) { BundleCapabilityAndLocation capability = (BundleCapabilityAndLocation) itBundle .next(); Map/* <String, String> */newCriteria = new HashMap/* <String, String> */(criteria); newCriteria.put(IvyPatternHelper.REVISION_KEY, capability.getVersion().toString()); tokenValues.addAll(listTokenValues(tokenSet, newCriteria)); } return tokenValues; } values.put(IvyPatternHelper.REVISION_KEY, rev); tokenSet.remove(IvyPatternHelper.CONF_KEY); String conf = (String) criteria.get(IvyPatternHelper.CONF_KEY); if (conf == null) { if (osgiType.equals(BundleInfo.PACKAGE_TYPE)) { values.put(IvyPatternHelper.CONF_KEY, BundleInfoAdapter.CONF_USE_PREFIX + module); return Collections./* <Map<String, String>> */singleton(values); } Set/* <BundleCapabilityAndLocation> */bundleCapabilities = getRepoDescriptor() .findModule(osgiType, module); if (bundleCapabilities == null) { return Collections.EMPTY_SET; } Version v; try { v = new Version(rev); } catch (ParseException e) { return Collections.EMPTY_SET; } BundleCapabilityAndLocation found = null; Iterator itBundle = bundleCapabilities.iterator(); while (itBundle.hasNext()) { BundleCapabilityAndLocation bundleCapability = (BundleCapabilityAndLocation) itBundle .next(); if (bundleCapability.getVersion().equals(v)) { found = bundleCapability; } } if (found == null) { return Collections.EMPTY_SET; } Set/* <Map<String, String>> */tokenValues = new HashSet/* <Map<String, String>> */(); List/* <String> */configurations = BundleInfoAdapter.getConfigurations(found .getBundleInfo()); for (int i = 0; i < configurations.size(); i++) { Map/* <String, String> */newCriteria = new HashMap/* <String, String> */(criteria); newCriteria.put(IvyPatternHelper.CONF_KEY, configurations.get(i)); tokenValues.add(newCriteria); } return tokenValues; } values.put(IvyPatternHelper.CONF_KEY, conf); return Collections./* <Map<String, String>> */singleton(values); } protected long get(Resource resource, File dest) throws IOException { Message.verbose("\t" + getName() + ": downloading " + resource.getName()); Message.debug("\t\tto " + dest); if (dest.getParentFile() != null) { dest.getParentFile().mkdirs(); } getRepository().get(resource.getName(), dest); return dest.length(); } protected Resource getResource(String source) throws IOException { return getRepository().getResource(source); } public void publish(Artifact artifact, File src, boolean overwrite) throws IOException { throw new UnsupportedOperationException(); } }
/* * Licensed to ObjectStyle LLC under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ObjectStyle LLC licenses * this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.bootique; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.Singleton; import io.bootique.annotation.Args; import io.bootique.annotation.DIConfigs; import io.bootique.annotation.DefaultCommand; import io.bootique.annotation.EnvironmentProperties; import io.bootique.annotation.EnvironmentVariables; import io.bootique.cli.Cli; import io.bootique.cli.CliFactory; import io.bootique.command.Command; import io.bootique.command.CommandDecorator; import io.bootique.command.CommandDispatchThreadFactory; import io.bootique.command.CommandManager; import io.bootique.command.CommandManagerBuilder; import io.bootique.command.CommandRefDecorated; import io.bootique.command.ExecutionPlanBuilder; import io.bootique.config.CliConfigurationSource; import io.bootique.config.ConfigurationFactory; import io.bootique.config.ConfigurationSource; import io.bootique.config.PolymorphicConfiguration; import io.bootique.config.TypesFactory; import io.bootique.env.DeclaredVariable; import io.bootique.env.DefaultEnvironment; import io.bootique.env.Environment; import io.bootique.help.DefaultHelpGenerator; import io.bootique.help.HelpCommand; import io.bootique.help.HelpGenerator; import io.bootique.help.config.ConfigHelpGenerator; import io.bootique.help.config.DefaultConfigHelpGenerator; import io.bootique.help.config.HelpConfigCommand; import io.bootique.jackson.DefaultJacksonService; import io.bootique.jackson.JacksonService; import io.bootique.jopt.JoptCliFactory; import io.bootique.log.BootLogger; import io.bootique.meta.application.ApplicationMetadata; import io.bootique.meta.application.OptionMetadata; import io.bootique.meta.config.ConfigHierarchyResolver; import io.bootique.meta.config.ConfigMetadataCompiler; import io.bootique.meta.module.ModulesMetadata; import io.bootique.meta.module.ModulesMetadataCompiler; import io.bootique.run.DefaultRunner; import io.bootique.run.Runner; import io.bootique.shutdown.ShutdownManager; import io.bootique.terminal.FixedWidthTerminal; import io.bootique.terminal.SttyTerminal; import io.bootique.terminal.Terminal; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Supplier; /** * The main {@link Module} of Bootique DI runtime. Declares a minimal set of * services needed for a Bootique app to start: services for parsing command * line, reading configuration, selectign and running a Command. */ public class BQCoreModule implements Module { // TODO: duplicate of FormattedAppender.MIN_LINE_WIDTH private static final int TTY_MIN_COLUMNS = 40; private static final int TTY_DEFAULT_COLUMNS = 80; /** * Properties are used to exclude system env vars and properties. * It's a duplicate of constants in io.bootique.test.junit.BQTestRuntimeBuilder */ private static final String EXCLUDE_SYSTEM_VARIABLES = "bq.core.excludeSystemVariables"; private static final String EXCLUDE_SYSTEM_PROPERTIES = "bq.core.excludeSystemProperties"; private String[] args; private ShutdownManager shutdownManager; private BootLogger bootLogger; private Supplier<Collection<BQModule>> modulesSource; private BQCoreModule() { } /** * @return a Builder instance to configure the module before using it to * initialize DI container. * @since 0.12 */ public static Builder builder() { return new Builder(); } /** * Returns an instance of {@link BQCoreModuleExtender} used by downstream modules to load custom extensions to the * Bootique core module. Should be invoked from a downstream Module's "configure" method. * * @param binder DI binder passed to the Module that invokes this method. * @return an instance of {@link BQCoreModuleExtender} that can be used to load custom extensions to the Bootique * core. * @since 0.22 */ public static BQCoreModuleExtender extend(Binder binder) { return new BQCoreModuleExtender(binder); } private static Optional<Command> defaultCommand(Injector injector) { // default is optional, so check via injector whether it is bound... Binding<Command> binding = injector.getExistingBinding(Key.get(Command.class, DefaultCommand.class)); return binding != null ? Optional.of(binding.getProvider().get()) : Optional.empty(); } @Override public void configure(Binder binder) { BQCoreModule.extend(binder) .initAllExtensions() .addOption(createConfigOption()) .addCommand(HelpConfigCommand.class); // bind instances binder.bind(BootLogger.class).toInstance(Objects.requireNonNull(bootLogger)); binder.bind(ShutdownManager.class).toInstance(Objects.requireNonNull(shutdownManager)); binder.bind(String[].class).annotatedWith(Args.class).toInstance(Objects.requireNonNull(args)); // too much code to create config factory.. extracting it in a provider // class... binder.bind(ConfigurationFactory.class).toProvider(JsonNodeConfigurationFactoryProvider.class).in(Singleton.class); } OptionMetadata createConfigOption() { return OptionMetadata .builder(CliConfigurationSource.CONFIG_OPTION, "Specifies YAML config location, which can be a file path or a URL.") .valueRequired("yaml_location").build(); } @Provides @Singleton JacksonService provideJacksonService(TypesFactory<PolymorphicConfiguration> typesFactory) { return new DefaultJacksonService(typesFactory.getTypes()); } @Provides @Singleton TypesFactory<PolymorphicConfiguration> provideConfigTypesFactory(BootLogger logger) { return new TypesFactory<>(getClass().getClassLoader(), PolymorphicConfiguration.class, logger); } @Provides @Singleton Runner provideRunner(Cli cli, CommandManager commandManager, ExecutionPlanBuilder execPlanBuilder) { return new DefaultRunner(cli, commandManager, execPlanBuilder); } @Provides @Singleton ConfigurationSource provideConfigurationSource(Cli cli, @DIConfigs Set<String> diConfigs, BootLogger bootLogger) { return CliConfigurationSource .builder(bootLogger) .diConfigs(diConfigs) .cliConfigs(cli) .build(); } @Provides @Singleton HelpCommand provideHelpCommand(BootLogger bootLogger, Provider<HelpGenerator> helpGeneratorProvider) { return new HelpCommand(bootLogger, helpGeneratorProvider); } @Provides @Singleton HelpConfigCommand provideHelpConfigCommand(BootLogger bootLogger, Provider<ConfigHelpGenerator> helpGeneratorProvider) { return new HelpConfigCommand(bootLogger, helpGeneratorProvider); } @Provides @Singleton CliFactory provideCliFactory( Provider<CommandManager> commandManagerProvider, ApplicationMetadata applicationMetadata) { return new JoptCliFactory(commandManagerProvider, applicationMetadata); } @Provides @Singleton Cli provideCli(CliFactory cliFactory, @Args String[] args) { return cliFactory.createCli(args); } @Provides @Singleton ExecutionPlanBuilder provideExecutionPlanBuilder( Provider<CliFactory> cliFactoryProvider, Provider<CommandManager> commandManagerProvider, Set<CommandRefDecorated> commandDecorators, BootLogger logger, ShutdownManager shutdownManager) { Provider<ExecutorService> executorProvider = () -> { ExecutorService service = Executors.newCachedThreadPool(new CommandDispatchThreadFactory()); shutdownManager.addShutdownHook(() -> service.shutdownNow()); return service; }; Map<Class<? extends Command>, CommandDecorator> merged = ExecutionPlanBuilder.mergeDecorators(commandDecorators); return new ExecutionPlanBuilder(cliFactoryProvider, commandManagerProvider, executorProvider, merged, logger); } @Provides @Singleton CommandManager provideCommandManager( Set<Command> commands, HelpCommand helpCommand, Injector injector) { return new CommandManagerBuilder(commands) .defaultCommand(defaultCommand(injector)) .helpCommand(helpCommand) .build(); } @Provides @Singleton HelpGenerator provideHelpGenerator(ApplicationMetadata application, Terminal terminal) { int maxColumns = terminal.getColumns(); if (maxColumns < TTY_MIN_COLUMNS) { maxColumns = TTY_DEFAULT_COLUMNS; } return new DefaultHelpGenerator(application, maxColumns); } @Provides @Singleton ConfigHelpGenerator provideConfigHelpGenerator(ModulesMetadata modulesMetadata, Terminal terminal) { int maxColumns = terminal.getColumns(); if (maxColumns < TTY_MIN_COLUMNS) { maxColumns = TTY_DEFAULT_COLUMNS; } return new DefaultConfigHelpGenerator(modulesMetadata, maxColumns); } @Provides @Singleton ConfigHierarchyResolver provideConfigHierarchyResolver(TypesFactory<PolymorphicConfiguration> typesFactory) { return ConfigHierarchyResolver.create(typesFactory.getTypes()); } @Provides @Singleton ModulesMetadata provideModulesMetadata(ConfigHierarchyResolver hierarchyResolver) { return new ModulesMetadataCompiler(new ConfigMetadataCompiler(hierarchyResolver::directSubclasses)) .compile(this.modulesSource != null ? modulesSource.get() : Collections.emptyList()); } @Provides @Singleton ApplicationMetadata provideApplicationMetadata( ApplicationDescription descriptionHolder, CommandManager commandManager, Set<OptionMetadata> options, Set<DeclaredVariable> declaredVars, ModulesMetadata modulesMetadata) { ApplicationMetadata.Builder builder = ApplicationMetadata .builder() .description(descriptionHolder.getDescription()) .addOptions(options); commandManager.getAllCommands().values().forEach(mc -> { if (!mc.isHidden() && !mc.isDefault()) { builder.addCommand(mc.getCommand().getMetadata()); } }); // merge default command options with top-level app options commandManager.getPublicDefaultCommand().ifPresent(c -> builder.addOptions(c.getMetadata().getOptions())); declaredVars.forEach(dv -> DeclaredVariableMetaCompiler .compileIfValid(dv, modulesMetadata) .ifPresent(builder::addVariable)); return builder.build(); } @Provides @Singleton Environment provideEnvironment( @EnvironmentProperties Map<String, String> diProperties, @EnvironmentVariables Map<String, String> diVars, Set<DeclaredVariable> declaredVariables) { DefaultEnvironment.Builder environment = DefaultEnvironment.builder(); if (Boolean.valueOf(diProperties.get(EXCLUDE_SYSTEM_PROPERTIES))) { environment.excludeSystemProperties(); } if (Boolean.valueOf(diProperties.containsKey(EXCLUDE_SYSTEM_VARIABLES))) { environment.excludeSystemVariables(); } return environment.diProperties(diProperties) .diVariables(diVars) .declaredVariables(declaredVariables) .build(); } @Provides @Singleton Terminal provideTerminal(BootLogger bootLogger) { // very simple OS test... boolean isUnix = "/".equals(System.getProperty("file.separator")); return isUnix ? new SttyTerminal(bootLogger) : new FixedWidthTerminal(TTY_DEFAULT_COLUMNS); } public static class Builder { private BQCoreModule module; private Builder() { this.module = new BQCoreModule(); } public BQCoreModule build() { return module; } public Builder bootLogger(BootLogger bootLogger) { module.bootLogger = bootLogger; return this; } public Builder shutdownManager(ShutdownManager shutdownManager) { module.shutdownManager = shutdownManager; return this; } /** * Sets a supplier of the app modules collection. It has to be provided externally by Bootique code that * assembles the stack. We have no way of discovering this information when inside the DI container. * * @param modulesSource a supplier of module collection. * @return this builder instance. * @since 0.21 */ public Builder moduleSource(Supplier<Collection<BQModule>> modulesSource) { module.modulesSource = modulesSource; return this; } public Builder args(String[] args) { module.args = args; return this; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.distributed.near; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import javax.cache.Cache; import javax.cache.CacheException; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteDataStreamer; import org.apache.ignite.IgniteException; import org.apache.ignite.binary.BinaryObject; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.affinity.AffinityFunction; import org.apache.ignite.cache.affinity.AffinityFunctionContext; import org.apache.ignite.cache.affinity.AffinityKeyMapped; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.SqlQuery; import org.apache.ignite.cache.query.annotations.QuerySqlField; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.util.GridRandom; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.util.AttributeNodeFilter; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheRebalanceMode.SYNC; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * Abstract test for queries over explicit partitions. */ public abstract class IgniteCacheDistributedPartitionQueryAbstractSelfTest extends GridCommonAbstractTest { /** Join query for test. */ private static final String JOIN_QRY = "select cl._KEY, de.depositId, de.regionId from " + "\"cl\".Client cl, \"de\".Deposit de, \"re\".Region re where cl.clientId=de.clientId and de.regionId=re._KEY"; /** Region node attribute name. */ private static final String REGION_ATTR_NAME = "reg"; /** Grids count. */ protected static final int GRIDS_COUNT = 10; /** Partitions per region distribution. */ protected static final int[] PARTS_PER_REGION = new int[] {10, 20, 30, 40, 24}; /** Unmapped region id. */ protected static final int UNMAPPED_REGION = PARTS_PER_REGION.length; /** Clients per partition. */ protected static final int CLIENTS_PER_PARTITION = 1; /** Total clients. */ private static final int TOTAL_CLIENTS; /** Affinity function to use on partitioned caches. */ private static final AffinityFunction AFFINITY = new RegionAwareAffinityFunction(); /** Partitions count. */ private static final int PARTS_COUNT; /** Regions to partitions mapping. */ protected static final NavigableMap<Integer, List<Integer>> REGION_TO_PART_MAP = new TreeMap<>(); /** Query threads count. */ protected static final int QUERY_THREADS_CNT = 4; /** Restarting threads count. */ protected static final int RESTART_THREADS_CNT = 2; /** Node stop time. */ protected static final int NODE_RESTART_TIME = 1_000; static { int total = 0, parts = 0, p = 0, regionId = 1; for (int regCnt : PARTS_PER_REGION) { total += regCnt * CLIENTS_PER_PARTITION; parts += regCnt; REGION_TO_PART_MAP.put(regionId++, Arrays.asList(p, regCnt)); p += regCnt; } /** Last region was left empty intentionally, see {@link #UNMAPPED_REGION} */ TOTAL_CLIENTS = total - PARTS_PER_REGION[PARTS_PER_REGION.length - 1] * CLIENTS_PER_PARTITION; PARTS_COUNT = parts; } /** Deposits per client. */ public static final int DEPOSITS_PER_CLIENT = 10; /** Rnd. */ protected GridRandom rnd = new GridRandom(); /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); DataStorageConfiguration memCfg = new DataStorageConfiguration().setDefaultDataRegionConfiguration( new DataRegionConfiguration().setMaxSize(20L * 1024 * 1024)); cfg.setDataStorageConfiguration(memCfg); /** Clients cache */ CacheConfiguration<ClientKey, Client> clientCfg = new CacheConfiguration<>(); clientCfg.setName("cl"); clientCfg.setWriteSynchronizationMode(FULL_SYNC); clientCfg.setAtomicityMode(TRANSACTIONAL); clientCfg.setRebalanceMode(SYNC); clientCfg.setBackups(2); clientCfg.setAffinity(AFFINITY); clientCfg.setIndexedTypes(ClientKey.class, Client.class); /** Deposits cache */ CacheConfiguration<DepositKey, Deposit> depoCfg = new CacheConfiguration<>(); depoCfg.setName("de"); depoCfg.setWriteSynchronizationMode(FULL_SYNC); depoCfg.setAtomicityMode(TRANSACTIONAL); depoCfg.setRebalanceMode(SYNC); depoCfg.setBackups(2); depoCfg.setAffinity(AFFINITY); depoCfg.setIndexedTypes(DepositKey.class, Deposit.class); /** Regions cache. Uses default affinity. */ CacheConfiguration<Integer, Region> regionCfg = new CacheConfiguration<>(); regionCfg.setName("re"); regionCfg.setWriteSynchronizationMode(FULL_SYNC); regionCfg.setAtomicityMode(TRANSACTIONAL); regionCfg.setRebalanceMode(SYNC); regionCfg.setCacheMode(CacheMode.REPLICATED); regionCfg.setIndexedTypes(Integer.class, Region.class); cfg.setCacheConfiguration(clientCfg, depoCfg, regionCfg); if (!"client".equals(gridName)) { Integer reg = regionForGrid(gridName); cfg.setUserAttributes(F.asMap(REGION_ATTR_NAME, reg)); log().info("Assigned region " + reg + " to grid " + gridName); } return cfg; } /** */ private static final class RegionAwareAffinityFunction implements AffinityFunction { /** {@inheritDoc} */ @Override public void reset() { // No-op. } /** {@inheritDoc} */ @Override public int partitions() { return PARTS_COUNT; } /** {@inheritDoc} */ @Override public int partition(Object key) { Integer regionId; if (key instanceof RegionKey) regionId = ((RegionKey)key).regionId; else if (key instanceof BinaryObject) { BinaryObject bo = (BinaryObject)key; regionId = bo.field("regionId"); } else throw new IgniteException("Unsupported key for region aware affinity"); List<Integer> range = REGION_TO_PART_MAP.get(regionId); Integer cnt = range.get(1); return U.safeAbs(key.hashCode() % cnt) + range.get(0); // Assign partition in region's range. } /** {@inheritDoc} */ @Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) { List<ClusterNode> nodes = affCtx.currentTopologySnapshot(); List<List<ClusterNode>> assignment = new ArrayList<>(PARTS_COUNT); for (int p = 0; p < PARTS_COUNT; p++) { // Get region for partition. int regionId = regionForPart(p); // Filter all nodes for region. AttributeNodeFilter f = new AttributeNodeFilter(REGION_ATTR_NAME, regionId); List<ClusterNode> regionNodes = new ArrayList<>(); for (ClusterNode node : nodes) if (f.apply(node)) regionNodes.add(node); final int cp = p; Collections.sort(regionNodes, new Comparator<ClusterNode>() { @Override public int compare(ClusterNode o1, ClusterNode o2) { return Long.compare(hash(cp, o1), hash(cp, o2)); } }); assignment.add(regionNodes); } return assignment; } /** {@inheritDoc} */ @Override public void removeNode(UUID nodeId) { // No-op. } /** * @param part Partition. */ protected int regionForPart(int part) { for (Map.Entry<Integer, List<Integer>> entry : REGION_TO_PART_MAP.entrySet()) { List<Integer> range = entry.getValue(); if (range.get(0) <= part && part < range.get(0) + range.get(1)) return entry.getKey(); } throw new IgniteException("Failed to find zone for partition"); } /** * @param part Partition. * @param obj Object. */ private long hash(int part, Object obj) { long x = ((long)part << 32) | obj.hashCode(); x ^= x >>> 12; x ^= x << 25; x ^= x >>> 27; return x * 2685821657736338717L; } } /** * Assigns a region to grid part. * * @param gridName Grid name. */ protected Integer regionForGrid(String gridName) { char c = gridName.charAt(gridName.length() - 1); switch (c) { case '0': return 1; case '1': case '2': return 2; case '3': case '4': case '5': return 3; default: return 4; } } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); int sum1 = 0; for (List<Integer> range : REGION_TO_PART_MAP.values()) sum1 += range.get(1); assertEquals("Illegal partition per region distribution", PARTS_COUNT, sum1); startGridsMultiThreaded(GRIDS_COUNT); startClientGrid("client"); // Fill caches. int clientId = 1; int depositId = 1; int regionId = 1; int p = 1; // Percents counter. Log message will be printed 10 times. try (IgniteDataStreamer<ClientKey, Client> clStr = grid(0).dataStreamer("cl"); IgniteDataStreamer<DepositKey, Deposit> depStr = grid(0).dataStreamer("de")) { for (int cnt : PARTS_PER_REGION) { // Last region was left empty intentionally. if (regionId < PARTS_PER_REGION.length) { for (int i = 0; i < cnt * CLIENTS_PER_PARTITION; i++) { ClientKey ck = new ClientKey(clientId, regionId); Client cl = new Client(); cl.firstName = "First_Name_" + clientId; cl.lastName = "Last_Name_" + clientId; cl.passport = clientId * 1_000; clStr.addData(ck, cl); for (int j = 0; j < DEPOSITS_PER_CLIENT; j++) { DepositKey dk = new DepositKey(depositId++, new ClientKey(clientId, regionId)); Deposit depo = new Deposit(); depo.amount = ThreadLocalRandom.current().nextLong(1_000_001); depStr.addData(dk, depo); } if (clientId / (float)TOTAL_CLIENTS >= p / 10f) { log().info("Loaded " + clientId + " of " + TOTAL_CLIENTS); p++; } clientId++; } } Region region = new Region(); region.name = "Region_" + regionId; region.code = regionId * 10; grid(0).cache("re").put(regionId, region); regionId++; } } } /** * @param orig Originator. */ protected void doTestRegionQuery(Ignite orig) { IgniteCache<ClientKey, Client> cl = orig.cache("cl"); for (int regionId = 1; regionId <= PARTS_PER_REGION.length; regionId++) { SqlQuery<ClientKey, Client> qry1 = new SqlQuery<>(Client.class, "regionId=?"); qry1.setArgs(regionId); List<Cache.Entry<ClientKey, Client>> clients1 = cl.query(qry1).getAll(); int expRegionCnt = regionId == 5 ? 0 : PARTS_PER_REGION[regionId - 1] * CLIENTS_PER_PARTITION; assertEquals("Region " + regionId + " count", expRegionCnt, clients1.size()); validateClients(regionId, clients1); // Repeat the same query with partition set condition. List<Integer> range = REGION_TO_PART_MAP.get(regionId); SqlQuery<ClientKey, Client> qry2 = new SqlQuery<>(Client.class, "1=1"); qry2.setPartitions(createRange(range.get(0), range.get(1))); try { List<Cache.Entry<ClientKey, Client>> clients2 = cl.query(qry2).getAll(); assertEquals("Region " + regionId + " count with partition set", expRegionCnt, clients2.size()); // Query must produce only results from single region. validateClients(regionId, clients2); if (regionId == UNMAPPED_REGION) fail(); } catch (CacheException ignored) { if (regionId != UNMAPPED_REGION) fail(); } } } /** */ protected int[] createRange(int start, int cnt) { int[] vals = new int[cnt]; for (int i = 0; i < cnt; i++) vals[i] = start + i; return vals; } /** * @param orig Originator. */ protected void doTestPartitionsQuery(Ignite orig) { IgniteCache<ClientKey, Client> cl = orig.cache("cl"); for (int regionId = 1; regionId <= PARTS_PER_REGION.length; regionId++) { log().info("Running test queries for region " + regionId); List<Integer> range = REGION_TO_PART_MAP.get(regionId); int[] parts = createRange(range.get(0), range.get(1)); int off = rnd.nextInt(parts.length); int p1 = parts[off], p2 = parts[(off + (1 + rnd.nextInt(parts.length - 1))) % parts.length]; log().info("Parts: " + p1 + " " + p2); SqlQuery<ClientKey, Client> qry = new SqlQuery<>(Client.class, "1=1"); qry.setPartitions(p1, p2); try { List<Cache.Entry<ClientKey, Client>> clients = cl.query(qry).getAll(); // Query must produce only results from two partitions. for (Cache.Entry<ClientKey, Client> client : clients) { int p = orig.affinity("cl").partition(client.getKey()); assertTrue("Incorrect partition for key", p == p1 || p == p2); } if (regionId == UNMAPPED_REGION) fail(); } catch (CacheException ignored) { if (regionId != UNMAPPED_REGION) fail(); } } } /** * @param orig Query originator. * @param regionIds Region ids. */ protected void doTestJoinQuery(Ignite orig, int... regionIds) { IgniteCache<ClientKey, Client> cl = orig.cache("cl"); if (regionIds == null) { regionIds = new int[PARTS_PER_REGION.length]; for (int i = 0; i < regionIds.length; i++) regionIds[i] = i + 1; } for (int regionId : regionIds) { List<Integer> range = REGION_TO_PART_MAP.get(regionId); SqlFieldsQuery qry = new SqlFieldsQuery(JOIN_QRY); int[] pSet = createRange(range.get(0), 1 + rnd.nextInt(range.get(1) - 1)); qry.setPartitions(pSet); try { List<List<?>> rows = cl.query(qry).getAll(); for (List<?> row : rows) { ClientKey key = (ClientKey)row.get(0); int p = orig.affinity("cl").partition(key); assertTrue(Arrays.binarySearch(pSet, p) >= 0); } // Query must produce only results from single region. for (List<?> row : rows) assertEquals("Region id", regionId, ((Integer)row.get(2)).intValue()); if (regionId == UNMAPPED_REGION) fail(); } catch (CacheException e) { if (X.hasCause(e, InterruptedException.class, IgniteInterruptedCheckedException.class)) return; // Allow interruptions. if (regionId != UNMAPPED_REGION) { e.printStackTrace(System.err); fail("Unexpected exception (see details above): " + e.getMessage()); } } } } /** * @param regionId Region id. * @param clients Clients. */ protected void validateClients(int regionId, List<Cache.Entry<ClientKey, Client>> clients) { for (Cache.Entry<ClientKey, Client> entry : clients) { List<Integer> range = REGION_TO_PART_MAP.get(regionId); int start = range.get(0) * CLIENTS_PER_PARTITION; int end = start + range.get(1) * CLIENTS_PER_PARTITION; int clientId = entry.getKey().clientId; assertTrue("Client id in range", start < clientId && start <= end); } } /** */ protected static class ClientKey extends RegionKey { /** Client id. */ @QuerySqlField(index = true) protected int clientId; /** * @param clientId Client id. * @param regionId Region id. */ public ClientKey(int clientId, int regionId) { this.clientId = clientId; this.regionId = regionId; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientKey clientKey = (ClientKey)o; return clientId == clientKey.clientId; } /** {@inheritDoc} */ @Override public int hashCode() { return clientId; } } /** */ protected static class DepositKey extends RegionKey { /** */ @QuerySqlField(index = true) protected int depositId; /** */ @QuerySqlField(index = true) protected int clientId; /** Client id. */ @AffinityKeyMapped protected ClientKey clientKey; /** * @param depositId Client id. * @param clientKey Client key. */ public DepositKey(int depositId, ClientKey clientKey) { this.depositId = depositId; this.clientId = clientKey.clientId; this.regionId = clientKey.regionId; this.clientKey = clientKey; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DepositKey that = (DepositKey)o; return depositId == that.depositId; } /** {@inheritDoc} */ @Override public int hashCode() { return depositId; } } /** */ protected static class RegionKey implements Serializable { /** Region id. */ @QuerySqlField(index = true) protected int regionId; } /** */ protected static class Client { /** */ @QuerySqlField protected String firstName; /** */ @QuerySqlField protected String lastName; /** */ @QuerySqlField(index = true) protected int passport; } /** */ protected static class Deposit { /** */ @QuerySqlField protected long amount; } /** */ protected static class Region { /** */ @QuerySqlField protected String name; /** */ @QuerySqlField protected int code; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.logging.log4j.Logger; import org.apache.geode.distributed.internal.DM; import org.apache.geode.distributed.internal.MembershipListener; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.Assert; import org.apache.geode.internal.cache.locks.TXLockId; import org.apache.geode.internal.i18n.LocalizedStrings; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LocalizedMessage; /** * TXFarSideCMTracker tracks received and processed TXCommitMessages, for transactions that contain * changes for DACK regions. Its main purpose is to allow recovery in the event that the VM which * orinated the TXCommitMessage exits the DistributedSystem. Tracking is done by using TXLockIds or * TXIds. It is designed for these failure cases: * * <ol> * * <li>The TX Originator has died during sending the second message which one or more of the * recipients (aka Far Siders) missed. To help in this case, each of the Far Siders will broadcast a * message to determine if the second commit message was received.</li> * * <li>The TX Grantor (the reservation system) has noticed that the TX Originator has died and * queries each of the Far Siders to determine if the reservation (aka <code>TXLockId</code>) given * to the TX Originator is no longer needed (the transaction has been processed)</li> * * <li>The TX Grantor has died and a new one is considering granting new reservations, but before * doing so must query all of the members to know if all the previous granted reservations (aka * <code>TXLockId</code>s are no longer needed (the transactions have been processed)</li> * * </ol> * * @since GemFire 4.0 * */ public class TXFarSideCMTracker { private static final Logger logger = LogService.getLogger(); private final Map txInProgress; private final Object txHistory[]; private int lastHistoryItem; // private final DM dm; /** * Constructor for TXFarSideCMTracker * * @param historySize The number of processed transactions to remember in the event that fellow * Far Siders did not receive the second message. */ public TXFarSideCMTracker(int historySize) { // InternalDistributedSystem sys = (InternalDistributedSystem) // CacheFactory.getAnyInstance().getDistributedSystem(); // this.dm = sys.getDistributionManager(); this.txInProgress = new HashMap(); this.txHistory = new Object[historySize]; this.lastHistoryItem = 0; } public int getHistorySize() { return this.txHistory.length; } /** * Answers fellow "Far Siders" question about an DACK transaction when the transaction originator * died before it sent the CommitProcess message. */ public boolean commitProcessReceived(Object key, DM dm) { // Assume that after the member has departed that we have all its pending // transaction messages if (key instanceof TXLockId) { TXLockId lk = (TXLockId) key; waitForMemberToDepart(lk.getMemberId(), dm); } else if (key instanceof TXId) { TXId id = (TXId) key; waitForMemberToDepart(id.getMemberId(), dm); } else { Assert.assertTrue(false, "TXTracker received an unknown key class: " + key.getClass()); } final TXCommitMessage mess; synchronized (this.txInProgress) { mess = (TXCommitMessage) this.txInProgress.get(key); if (null != mess && mess.isProcessing()) { return true; } for (int i = this.txHistory.length - 1; i >= 0; --i) { if (key.equals(this.txHistory[i])) { return true; } } } if (mess != null) { synchronized (mess) { if (!mess.isProcessing()) { // Prevent any potential future processing // of this message mess.setDontProcess(); return false; } else { return true; } } } return false; } /** * Answers new Grantor query regarding whether it can start handing out new locks. Waits until * txInProgress is empty. */ public void waitForAllToProcess() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); // wisest to do this before the synchronize below // Assume that a thread interrupt is only sent in the // case of a shutdown, in that case we don't need to wait // around any longer, propigating the interrupt is reasonable behavior synchronized (this.txInProgress) { while (!this.txInProgress.isEmpty()) { this.txInProgress.wait(); } } } /** * Answers existing Grantor's question about the status of a reservation/lock given to a * departed/ing Originator (this will most likely be called nearly the same time as * commitProcessReceived */ public void waitToProcess(TXLockId lk, DM dm) { waitForMemberToDepart(lk.getMemberId(), dm); final TXCommitMessage mess; synchronized (this.txInProgress) { mess = (TXCommitMessage) this.txInProgress.get(lk); } if (mess != null) { synchronized (mess) { // tx in progress, we must wait until its done while (!mess.wasProcessed()) { try { mess.wait(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); logger.error(LocalizedMessage.create( LocalizedStrings.TxFarSideTracker_WAITING_TO_COMPLETE_ON_MESSAGE_0_CAUGHT_AN_INTERRUPTED_EXCEPTION, mess), ie); break; } } } } else { // tx may have completed for (int i = this.txHistory.length - 1; i >= 0; --i) { if (lk.equals(this.txHistory[i])) { return; } } } } /** * Register a <code>MemberhipListener</code>, wait until the member is gone. */ private void waitForMemberToDepart(final InternalDistributedMember memberId, DM dm) { if (!dm.getDistributionManagerIds().contains(memberId)) { return; } final Object lock = new Object(); final MembershipListener memEar = new MembershipListener() { // MembershipListener implementation public void memberJoined(InternalDistributedMember id) {} public void memberSuspect(InternalDistributedMember id, InternalDistributedMember whoSuspected, String reason) {} public void memberDeparted(InternalDistributedMember id, boolean crashed) { if (memberId.equals(id)) { synchronized (lock) { lock.notifyAll(); } } } public void quorumLost(Set<InternalDistributedMember> failures, List<InternalDistributedMember> remaining) {} }; try { Set memberSet = dm.addMembershipListenerAndGetDistributionManagerIds(memEar); // Still need to wait synchronized (lock) { while (memberSet.contains(memberId)) { try { lock.wait(); memberSet = dm.getDistributionManagerIds(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // TODO Log an error here return; } } } // synchronized memberId } finally { // Its gone, we can proceed dm.removeMembershipListener(memEar); } } /** * Indicate that the transaction message has been processed and to place it in the transaction * history */ public TXCommitMessage processed(TXCommitMessage processedMess) { final TXCommitMessage mess; final Object key = processedMess.getTrackerKey(); synchronized (this.txInProgress) { mess = (TXCommitMessage) this.txInProgress.remove(key); if (mess != null) { this.txHistory[this.lastHistoryItem++] = key; if (lastHistoryItem >= txHistory.length) { lastHistoryItem = 0; } // For any waitForAllToComplete if (txInProgress.isEmpty()) { this.txInProgress.notifyAll(); } } } if (mess != null) { synchronized (mess) { mess.setProcessed(true); // For any waitToComplete mess.notifyAll(); } } return mess; } /** * Indicate that this message is never going to be processed, typically used in the case where * none of the FarSiders received the CommitProcessMessage **/ public void removeMessage(TXCommitMessage deadMess) { synchronized (this.txInProgress) { this.txInProgress.remove(deadMess.getTrackerKey()); // For any waitForAllToComplete if (txInProgress.isEmpty()) { this.txInProgress.notifyAll(); } } } /** * Retrieve the commit message associated with the lock */ public TXCommitMessage get(Object key) { final TXCommitMessage mess; synchronized (this.txInProgress) { mess = (TXCommitMessage) this.txInProgress.get(key); } return mess; } public TXCommitMessage waitForMessage(Object key, DM dm) { TXCommitMessage msg = null; synchronized (this.txInProgress) { msg = (TXCommitMessage) this.txInProgress.get(key); while (msg == null) { try { dm.getSystem().getCancelCriterion().checkCancelInProgress(null); this.txInProgress.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } msg = (TXCommitMessage) this.txInProgress.get(key); } } return msg; } /** * The transcation commit message has been received */ public void add(TXCommitMessage msg) { synchronized (this.txInProgress) { final Object key = msg.getTrackerKey(); if (key == null) { Assert.assertTrue(false, "TXFarSideCMTracker must have a non-null key for message " + msg); } this.txInProgress.put(key, msg); this.txInProgress.notifyAll(); } } // TODO we really need to keep around only one msg for each thread on a client private Map<TXId, TXCommitMessage> failoverMap = Collections.synchronizedMap(new LinkedHashMap<TXId, TXCommitMessage>() { protected boolean removeEldestEntry(Entry eldest) { return size() > TXManagerImpl.FAILOVER_TX_MAP_SIZE; }; }); public void saveTXForClientFailover(TXId txId, TXCommitMessage msg) { this.failoverMap.put(txId, msg); } public TXCommitMessage getTXCommitMessage(TXId txId) { return this.failoverMap.get(txId); } /** * a static TXFarSideCMTracker is held by TXCommitMessage and is cleared when the cache has * finished closing */ public void clearForCacheClose() { this.failoverMap.clear(); this.lastHistoryItem = 0; Arrays.fill(this.txHistory, null); } }
/* * RandomGUID * @version 1.2.1 11/05/02 * @author Marc A. Mnich * * From www.JavaExchange.com, Open Software licensing * * 11/05/02 -- Performance enhancement from Mike Dubman. * Moved InetAddr.getLocal to static block. Mike has measured * a 10 fold improvement in run time. * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object * caused duplicate GUIDs to be produced. Random object * is now only created once per JVM. * 01/19/02 -- Modified random seeding and added new constructor * to allow secure random feature. * 01/14/02 -- Added random function seeding with JVM run time * */ package com.javaexchange; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; /* * In the multitude of java GUID generators, I found none that guaranteed * randomness. GUIDs are guaranteed to be globally unique by using ethernet * MACs, IP addresses, time elements, and sequential numbers. GUIDs are not * expected to be random and most often are easy/possible to guess given a * sample from a given generator. SQL Server, for example generates GUID that * are unique but sequencial within a given instance. * * GUIDs can be used as security devices to hide things such as files within a * filesystem where listings are unavailable (e.g. files that are served up from * a Web server with indexing turned off). This may be desireable in cases where * standard authentication is not appropriate. In this scenario, the RandomGUIDs * are used as directories. Another example is the use of GUIDs for primary keys * in a database where you want to ensure that the keys are secret. Random GUIDs * can then be used in a URL to prevent hackers (or users) from accessing * records by guessing or simply by incrementing sequential numbers. * * There are many other possiblities of using GUIDs in the realm of security and * encryption where the element of randomness is important. This class was * written for these purposes but can also be used as a general purpose GUID * generator as well. * * RandomGUID generates truly random GUIDs by using the system's IP address * (name/IP), system time in milliseconds (as an integer), and a very large * random number joined together in a single String that is passed through an * MD5 hash. The IP address and system time make the MD5 seed globally unique * and the random number guarantees that the generated GUIDs will have no * discernable pattern and cannot be guessed given any number of previously * generated GUIDs. It is generally not possible to access the seed information * (IP, time, random number) from the resulting GUIDs as the MD5 hash algorithm * provides one way encryption. * * ----> Security of RandomGUID: <----- RandomGUID can be called one of two ways -- * with the basic java Random number generator or a cryptographically strong * random generator (SecureRandom). The choice is offered because the secure * random generator takes about 3.5 times longer to generate its random numbers * and this performance hit may not be worth the added security especially * considering the basic generator is seeded with a cryptographically strong * random seed. * * Seeding the basic generator in this way effectively decouples the random * numbers from the time component making it virtually impossible to predict the * random number component even if one had absolute knowledge of the System * time. Thanks to Ashutosh Narhari for the suggestion of using the static * method to prime the basic random generator. * * Using the secure random option, this class compies with the statistical * random number generator tests specified in FIPS 140-2, Security Requirements * for Cryptographic Modules, secition 4.9.1. * * I converted all the pieces of the seed to a String before handing it over to * the MD5 hash so that you could print it out to make sure it contains the data * you expect to see and to give a nice warm fuzzy. If you need better * performance, you may want to stick to byte[] arrays. * * I believe that it is important that the algorithm for generating random GUIDs * be open for inspection and modification. This class is free for all uses. - * Marc */ public class RandomGUID extends Object { public String valueBeforeMD5 = ""; public String valueAfterMD5 = ""; private static Random myRand; private static SecureRandom mySecureRand; private static String s_id; /* * Static block to take care of one time secureRandom seed. It takes a few * seconds to initialize SecureRandom. You might want to consider removing * this static block or replacing it with a "time since first loaded" seed * to reduce this time. This block will run only once per JVM instance. */ static { mySecureRand = new SecureRandom(); long secureInitializer = mySecureRand.nextLong(); myRand = new Random(secureInitializer); try { s_id = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { e.printStackTrace(); } } /* * Default constructor. With no specification of security option, this * constructor defaults to lower security, high performance. */ public RandomGUID() { getRandomGUID(false); } /* * Constructor with security option. Setting secure true enables each random * number generated to be cryptographically strong. Secure false defaults to * the standard Random function seeded with a single cryptographically * strong random number. */ public RandomGUID(boolean secure) { getRandomGUID(secure); } /* * Method to generate the random GUID */ private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } // This StringBuffer can be a long as you need; the MD5 // hash will always return 128 bits. You can change // the seed to include anything you want here. // You could even stream a file through the MD5 making // the odds of guessing it at least as great as that // of guessing the contents of the file! sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } /* * Convert to the standard format for GUID (Useful for SQL Server * UniqueIdentifiers, etc.) Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6 */ public String toString() { String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); } /* * Demonstraton and self test of class */ public static void main(String args[]) { for (int i = 0; i < 100; i++) { RandomGUID myGUID = new RandomGUID(); System.out.println("Seeding String=" + myGUID.valueBeforeMD5); System.out.println("rawGUID=" + myGUID.valueAfterMD5); System.out.println("RandomGUID=" + myGUID.toString()); } } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.configurable; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.UnnamedConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Getter; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.impl.VcsDescriptor; import com.intellij.openapi.vcs.impl.projectlevelman.AllVcses; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.util.HashMap; import java.util.Map; public class VcsConfigurationsDialog extends DialogWrapper{ private JList myVcses; private JPanel myVcsConfigurationPanel; private final Project myProject; private JPanel myVersionControlConfigurationsPanel; private static final String NONE = VcsBundle.message("none.vcs.presentation"); private final Map<String, UnnamedConfigurable> myVcsNameToConfigurableMap = new HashMap<String, UnnamedConfigurable>(); private static final ColoredListCellRenderer VCS_LIST_RENDERER = new ColoredListCellRenderer() { protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { String name = value == null ? NONE : ((VcsDescriptor) value).getDisplayName(); append(name, new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, list.getForeground())); } }; private JScrollPane myVcsesScrollPane; @Nullable private final JComboBox myVcsesToUpdate; public VcsConfigurationsDialog(Project project, @Nullable JComboBox vcses, VcsDescriptor selectedVcs) { super(project, false); myProject = project; VcsDescriptor[] abstractVcses = collectAvailableNames(); initList(abstractVcses); initVcsConfigurable(abstractVcses); updateConfiguration(); myVcsesToUpdate = vcses; for (String vcsName : myVcsNameToConfigurableMap.keySet()) { UnnamedConfigurable configurable = myVcsNameToConfigurableMap.get(vcsName); if (configurable != null && configurable.isModified()) configurable.reset(); } updateConfiguration(); if (selectedVcs != null){ myVcses.setSelectedValue(selectedVcs, true); } init(); setTitle(VcsBundle.message("dialog.title.version.control.configurations")); } private void updateConfiguration() { int selectedIndex = myVcses.getSelectionModel().getMinSelectionIndex(); final VcsDescriptor currentVcs; currentVcs = selectedIndex >= 0 ? (VcsDescriptor)(myVcses.getModel()).getElementAt(selectedIndex) : null; String currentName = currentVcs == null ? NONE : currentVcs.getName(); if (currentVcs != null) { final UnnamedConfigurable unnamedConfigurable = myVcsNameToConfigurableMap.get(currentName); unnamedConfigurable.createComponent(); unnamedConfigurable.reset(); } final CardLayout cardLayout = (CardLayout)myVcsConfigurationPanel.getLayout(); cardLayout.show(myVcsConfigurationPanel, currentName); } private void initVcsConfigurable(VcsDescriptor[] vcses) { myVcsConfigurationPanel.setLayout(new CardLayout()); MyNullConfigurable nullConfigurable = new MyNullConfigurable(); myVcsNameToConfigurableMap.put(NONE, nullConfigurable); myVcsConfigurationPanel.add(nullConfigurable.createComponent(), NONE); for (VcsDescriptor vcs : vcses) { addConfigurationPanelFor(vcs); } } private void addConfigurationPanelFor(final VcsDescriptor vcs) { String name = vcs.getName(); final JPanel parentPanel = new JPanel(); final LazyConfigurable lazyConfigurable = new LazyConfigurable(new Getter<Configurable>() { @Override public Configurable get() { return AllVcses.getInstance(myProject).getByName(vcs.getName()).getConfigurable(); } }, parentPanel); myVcsNameToConfigurableMap.put(name, lazyConfigurable); myVcsConfigurationPanel.add(parentPanel, name); } private void initList(VcsDescriptor[] names) { DefaultListModel model = new DefaultListModel(); for (VcsDescriptor name : names) { model.addElement(name); } myVcses.setModel(model); myVcses.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { updateConfiguration(); } }); myVcses.setCellRenderer(VCS_LIST_RENDERER); myVcsesScrollPane.setMinimumSize(myVcsesScrollPane.getPreferredSize()); } private VcsDescriptor[] collectAvailableNames() { return ProjectLevelVcsManager.getInstance(myProject).getAllVcss(); } protected JComponent createCenterPanel() { return myVersionControlConfigurationsPanel; } protected void doOKAction() { for (String vcsName : myVcsNameToConfigurableMap.keySet()) { UnnamedConfigurable configurable = myVcsNameToConfigurableMap.get(vcsName); if (configurable != null && configurable.isModified()) { try { configurable.apply(); } catch (ConfigurationException e) { Messages.showErrorDialog(VcsBundle.message("message.text.unable.to.save.settings", e.getMessage()), VcsBundle.message("message.title.unable.to.save.settings")); } } } final JComboBox vcsesToUpdate = myVcsesToUpdate; if (vcsesToUpdate != null) { final VcsDescriptor wrapper = (VcsDescriptor) myVcses.getSelectedValue(); vcsesToUpdate.setSelectedItem(wrapper); final ComboBoxModel model = vcsesToUpdate.getModel(); for(int i = 0; i < model.getSize(); i++){ final Object vcsWrapper = model.getElementAt(i); if (vcsWrapper instanceof VcsDescriptor){ final VcsDescriptor defaultVcsWrapper = (VcsDescriptor) vcsWrapper; if (defaultVcsWrapper.equals(wrapper)){ vcsesToUpdate.setSelectedIndex(i); break; } } } } super.doOKAction(); } protected void dispose() { myVcses.setCellRenderer(new DefaultListCellRenderer()); super.dispose(); } private static class MyNullConfigurable implements Configurable { public String getDisplayName() { return NONE; } public String getHelpTopic() { return "project.propVCSSupport"; } public JComponent createComponent() { return new JPanel(); } public boolean isModified() { return false; } public void apply() throws ConfigurationException { } public void reset() { } public void disposeUIResources() { } } }
package org.roaringbitmap; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.Random; import static org.junit.jupiter.api.Assertions.*; public class TestRange { @Test public void flip64() { RoaringBitmap rb = new RoaringBitmap(); rb.add(0); rb.flip(1L, 2L); IntIterator i = rb.getIntIterator(); assertEquals(0, i.next()); assertEquals(1, i.next()); assertFalse(i.hasNext()); } private static int fillWithRandomBits(final RoaringBitmap bitmap, final BitSet bitset, final int bits) { int added = 0; Random r = new Random(1011); for (int j = 0; j < bits; j++) { if (r.nextBoolean()) { added++; bitmap.add(j); bitset.set(j); } } return added; } @Test public void doubleadd() { RoaringBitmap rb = new RoaringBitmap(); rb.add(65533L, 65536L); rb.add(65530L, 65536L); BitSet bs = new BitSet(); bs.set(65530, 65536); assertTrue(TestRoaringBitmap.equals(bs, rb)); rb.remove(65530L, 65536L); assertEquals(0, rb.getCardinality()); } @Test public void rangeAddRemoveBig() { final int numCases = 5000; RoaringBitmap rbstatic = new RoaringBitmap(); final RoaringBitmap rbinplace = new RoaringBitmap(); final BitSet bs = new BitSet(); final Random r = new Random(3333); long start, end; for (int i = 0; i < numCases; ++i) { start = r.nextInt(65536 * 20); end = r.nextInt(65536 * 20); if (start > end) { long tmp = start; start = end; end = tmp; } rbinplace.add(start, end); rbstatic = RoaringBitmap.add(rbstatic, start, end); bs.set((int)start, (int)end); // start = r.nextInt(65536 * 20); end = r.nextInt(65536 * 20); if (start > end) { long tmp = start; start = end; end = tmp; } rbinplace.remove(start, end); rbstatic = RoaringBitmap.remove(rbstatic, start, end); bs.clear((int)start, (int)end); // start = r.nextInt(20) * 65536; end = r.nextInt(65536 * 20); if (start > end) { long tmp = start; start = end; end = tmp; } rbinplace.add(start, end); rbstatic = RoaringBitmap.add(rbstatic, start, end); bs.set((int)start, (int)end); // start = r.nextInt(65536 * 20); end = r.nextInt(20) * 65536; if (start > end) { long tmp = start; start = end; end = tmp; } rbinplace.add(start, end); rbstatic = RoaringBitmap.add(rbstatic, start, end); bs.set((int)start, (int)end); // start = r.nextInt(20) * 65536; end = r.nextInt(65536 * 20); if (start > end) { long tmp = start; start = end; end = tmp; } rbinplace.remove(start, end); rbstatic = RoaringBitmap.remove(rbstatic, start, end); bs.clear((int)start, (int)end); // start = r.nextInt(65536 * 20); end = r.nextInt(20) * 65536; if (start > end) { long tmp = start; start = end; end = tmp; } rbinplace.remove(start, end); rbstatic = RoaringBitmap.remove(rbstatic, start, end); bs.clear((int)start, (int)end); } assertTrue(TestRoaringBitmap.equals(bs, rbstatic)); assertTrue(TestRoaringBitmap.equals(bs, rbinplace)); assertEquals(rbinplace, rbstatic); } @Test public void setRemoveTest1() { final BitSet bs = new BitSet(); RoaringBitmap rb = new RoaringBitmap(); bs.set(0, 1000000); rb.add(0L, 1000000L); rb.remove(43022L, 392542L); bs.clear(43022, 392542); assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setRemoveTest2() { final BitSet bs = new BitSet(); RoaringBitmap rb = new RoaringBitmap(); bs.set(43022, 392542); rb.add(43022L, 392542L); rb.remove(43022L, 392542L); bs.clear(43022, 392542); assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest1() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(100000L, 200000L); // in-place on empty bitmap final int rbcard = rb.getCardinality(); assertEquals(100000, rbcard); final BitSet bs = new BitSet(); for (int i = 100000; i < 200000; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest1A() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 100000L, 200000L); final int rbcard = rb1.getCardinality(); assertEquals(100000, rbcard); assertEquals(0, rb.getCardinality()); final BitSet bs = new BitSet(); assertTrue(TestRoaringBitmap.equals(bs, rb)); // still empty? for (int i = 100000; i < 200000; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb1)); } @Test public void setTest2() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(100000L, 100000L); final int rbcard = rb.getCardinality(); assertEquals(0, rbcard); final BitSet bs = new BitSet(); assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest2A() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 100000L, 100000L); rb.add(1); // will not affect rb1 (no shared container) final int rbcard = rb1.getCardinality(); assertEquals(0, rbcard); assertEquals(1, rb.getCardinality()); final BitSet bs = new BitSet(); assertTrue(TestRoaringBitmap.equals(bs, rb1)); bs.set(1); assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest3() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(0L, 65536L); final int rbcard = rb.getCardinality(); assertEquals(65536, rbcard); final BitSet bs = new BitSet(); for (int i = 0; i < 65536; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest3A() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 100000L, 200000L); final RoaringBitmap rb2 = RoaringBitmap.add(rb1, 500000L, 600000L); final int rbcard = rb2.getCardinality(); assertEquals(200000, rbcard); final BitSet bs = new BitSet(); for (int i = 100000; i < 200000; ++i) { bs.set(i); } for (int i = 500000; i < 600000; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void setTest4() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(100000L, 200000L); rb.add(65536L, 4 * 65536L); final int rbcard = rb.getCardinality(); assertEquals(196608, rbcard); final BitSet bs = new BitSet(); for (int i = 65536; i < 4 * 65536; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest4A() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 100000L, 200000L); final RoaringBitmap rb2 = RoaringBitmap.add(rb1, 65536L, 4 * 65536L); final int rbcard = rb2.getCardinality(); assertEquals(196608, rbcard); final BitSet bs = new BitSet(); for (int i = 65536; i < 4 * 65536; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void setTest5() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(500L, 65536L * 3 + 500); rb.add(65536L, 65536L * 3); final int rbcard = rb.getCardinality(); assertEquals(196608, rbcard); final BitSet bs = new BitSet(); for (int i = 500; i < 65536 * 3 + 500; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest5A() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 100000L, 500000L); final RoaringBitmap rb2 = RoaringBitmap.add(rb1, 65536L, 120000L); final int rbcard = rb2.getCardinality(); assertEquals(434464, rbcard); BitSet bs = new BitSet(); for (int i = 65536; i < 500000; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void setTest6() { // fits evenly on big end, multiple containers final RoaringBitmap rb = new RoaringBitmap(); rb.add(100000L, 132000L); rb.add(3 * 65536L, 4 * 65536L); final int rbcard = rb.getCardinality(); assertEquals(97536, rbcard); final BitSet bs = new BitSet(); for (int i = 100000; i < 132000; ++i) { bs.set(i); } for (int i = 3 * 65536; i < 4 * 65536; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest6A() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 100000L, 132000L); final RoaringBitmap rb2 = RoaringBitmap.add(rb1, 3 * 65536L, 4 * 65536L); final int rbcard = rb2.getCardinality(); assertEquals(97536, rbcard); final BitSet bs = new BitSet(); for (int i = 100000; i < 132000; ++i) { bs.set(i); } for (int i = 3 * 65536; i < 4 * 65536; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void setTest7() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(10L, 50L); rb.add(1L, 9L); rb.add(130L, 185L); rb.add(6407L, 6460L); rb.add(325L, 380L); rb.add((65536L * 3) + 3, (65536L * 3) + 60); rb.add(65536L * 3 + 195, 65536L * 3 + 245); final int rbcard = rb.getCardinality(); assertEquals(318, rbcard); final BitSet bs = new BitSet(); for (int i = 10; i < 50; ++i) { bs.set(i); } for (int i = 1; i < 9; ++i) { bs.set(i); } for (int i = 130; i < 185; ++i) { bs.set(i); } for (int i = 325; i < 380; ++i) { bs.set(i); } for (int i = 6407; i < 6460; ++i) { bs.set(i); } for (int i = 65536 * 3 + 3; i < 65536 * 3 + 60; ++i) { bs.set(i); } for (int i = 65536 * 3 + 195; i < 65536 * 3 + 245; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTest7A() { final RoaringBitmap rb = new RoaringBitmap(); final BitSet bs = new BitSet(); assertTrue(TestRoaringBitmap.equals(bs, rb)); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 10L, 50L); bs.set(10, 50); rb.add(10L, 50L); assertEquals(rb1, rb); assertTrue(TestRoaringBitmap.equals(bs, rb1)); RoaringBitmap rb2 = RoaringBitmap.add(rb1, 130L, 185L); bs.set(130, 185); rb.add(130L, 185L); assertEquals(rb2, rb); assertTrue(TestRoaringBitmap.equals(bs, rb2)); RoaringBitmap rb3 = RoaringBitmap.add(rb2, 6407L, 6460L); bs.set(6407, 6460); assertTrue(TestRoaringBitmap.equals(bs, rb3)); rb2.add(6407L, 6460L); assertEquals(rb2, rb3); rb3 = RoaringBitmap.add(rb3, (65536L * 3) + 3, (65536L * 3) + 60); rb2.add((65536L * 3) + 3, (65536L * 3) + 60); bs.set((65536 * 3) + 3, (65536 * 3) + 60); assertEquals(rb2, rb3); assertTrue(TestRoaringBitmap.equals(bs, rb3)); rb3 = RoaringBitmap.add(rb3, 65536L * 3 + 195, 65536L * 3 + 245); bs.set(65536 * 3 + 195, 65536 * 3 + 245); rb2.add(65536L * 3 + 195, 65536L * 3 + 245); assertEquals(rb2, rb3); assertTrue(TestRoaringBitmap.equals(bs, rb3)); final int rbcard = rb3.getCardinality(); assertEquals(255, rbcard); // now removing rb3 = RoaringBitmap.remove(rb3, 65536L * 3 + 195, 65536L * 3 + 245); bs.clear(65536 * 3 + 195, 65536 * 3 + 245); rb2.remove(65536L * 3 + 195, 65536L * 3 + 245); assertEquals(rb2, rb3); assertTrue(TestRoaringBitmap.equals(bs, rb3)); rb3 = RoaringBitmap.remove(rb3, (65536L * 3) + 3, (65536L * 3) + 60); bs.clear((65536 * 3) + 3, (65536 * 3) + 60); rb2.remove((65536L * 3) + 3, (65536L * 3) + 60); assertEquals(rb2, rb3); assertTrue(TestRoaringBitmap.equals(bs, rb3)); rb3 = RoaringBitmap.remove(rb3, 6407L, 6460L); bs.clear(6407, 6460); rb2.remove(6407L, 6460L); assertEquals(rb2, rb3); assertTrue(TestRoaringBitmap.equals(bs, rb3)); rb2 = RoaringBitmap.remove(rb1, 130L, 185L); bs.clear(130, 185); rb.remove(130L, 185L); assertEquals(rb2, rb); assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void setTest8() { final RoaringBitmap rb = new RoaringBitmap(); for (int i = 0; i < 5; i++) { for (long j = 0; j < 1024; j++) { rb.add(i * (1 << 16) + j * 64 + 2, i * (1 << 16) + j * 64 + 63); } } final int rbcard = rb.getCardinality(); assertEquals(312320, rbcard); final BitSet bs = new BitSet(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 1024; j++) { bs.set(i * (1 << 16) + j * 64 + 2, i * (1 << 16) + j * 64 + 63); } } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTestArrayContainer() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(500L, 3000L); rb.add(65536L, 66000L); final int rbcard = rb.getCardinality(); assertEquals(2964, rbcard); BitSet bs = new BitSet(); for (int i = 500; i < 3000; ++i) { bs.set(i); } for (int i = 65536; i < 66000; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTestArrayContainerA() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 500L, 3000L); final RoaringBitmap rb2 = RoaringBitmap.add(rb1, 65536L, 66000L); final int rbcard = rb2.getCardinality(); assertEquals(2964, rbcard); BitSet bs = new BitSet(); for (int i = 500; i < 3000; ++i) { bs.set(i); } for (int i = 65536; i < 66000; ++i) { bs.set(i); } assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void setTestSinglePonits() { final RoaringBitmap rb = new RoaringBitmap(); rb.add(500L, 501L); rb.add(65536L, 65537L); final int rbcard = rb.getCardinality(); assertEquals(2, rbcard); BitSet bs = new BitSet(); bs.set(500); bs.set(65536); assertTrue(TestRoaringBitmap.equals(bs, rb)); } @Test public void setTestSinglePonitsA() { final RoaringBitmap rb = new RoaringBitmap(); final RoaringBitmap rb1 = RoaringBitmap.add(rb, 500L, 501L); final RoaringBitmap rb2 = RoaringBitmap.add(rb1, 65536L, 65537L); final int rbcard = rb2.getCardinality(); assertEquals(2, rbcard); BitSet bs = new BitSet(); bs.set(500); bs.set(65536); assertTrue(TestRoaringBitmap.equals(bs, rb2)); } @Test public void testClearRanges() { long N = 16; for (long end = 1; end < N; ++end) { for (long start = 0; start < end; ++start) { RoaringBitmap bs1 = new RoaringBitmap(); bs1.add(0L, N); for (int k = (int) start; k < end; ++k) { bs1.remove(k); } RoaringBitmap bs2 = new RoaringBitmap(); bs2.add(0L, N); bs2.remove(start, end); assertEquals(bs1, bs2); } } } @Test public void testFlipRanges() { int N = 256; for (long end = 1; end < N; ++end) { for (long start = 0; start < end; ++start) { RoaringBitmap bs1 = new RoaringBitmap(); for (int k = (int) start; k < end; ++k) { bs1.flip(k); } RoaringBitmap bs2 = new RoaringBitmap(); bs2.flip(start, end); assertEquals(bs2.getCardinality(), end - start); assertEquals(bs1, bs2); } } } @Test public void testRangeRemoval() { final RoaringBitmap bitmap = new RoaringBitmap(); bitmap.add(1); assertTrue((bitmap.getCardinality() == 1) && bitmap.contains(1)); bitmap.runOptimize(); assertTrue((bitmap.getCardinality() == 1) && bitmap.contains(1)); bitmap.removeRunCompression(); assertTrue((bitmap.getCardinality() == 1) && bitmap.contains(1)); bitmap.remove(0L, 1L); // should do nothing assertTrue((bitmap.getCardinality() == 1) && bitmap.contains(1)); bitmap.remove(1L, 2L); bitmap.remove(1L, 2L); // should clear [1,2) assertTrue(bitmap.isEmpty()); } @Test public void testRangeRemovalWithEightBitsAndRunlengthEncoding1() { final RoaringBitmap bitmap = new RoaringBitmap(); bitmap.add(1); // index 1 bitmap.add(2); bitmap.add(3); bitmap.add(4); bitmap.add(5); bitmap.add(7); // index 7 bitmap.runOptimize(); // should remove from index 0 to 7 bitmap.remove(0L, 8L); assertTrue(bitmap.isEmpty()); } @Test public void testRangeRemovalWithEightBitsAndRunlengthEncoding2() { final RoaringBitmap bitmap = new RoaringBitmap(); bitmap.add(1); // index 1 bitmap.add(2); bitmap.add(3); bitmap.add(4); bitmap.add(5); bitmap.add(7); // index 7 bitmap.runOptimize(); bitmap.removeRunCompression(); assertFalse(bitmap.hasRunCompression()); // should remove from index 0 to 7 bitmap.remove(0L, 8L); assertTrue(bitmap.isEmpty()); } private void testRangeRemovalWithRandomBits(boolean withRunCompression) { final int iterations = 4096; final int bits = 8; for (int i = 0; i < iterations; i++) { final BitSet bitset = new BitSet(bits); final RoaringBitmap bitmap = new RoaringBitmap(); // check, if empty assertTrue(bitset.isEmpty()); assertTrue(bitmap.isEmpty()); // fill with random bits final int added = fillWithRandomBits(bitmap, bitset, bits); // check for cardinalities and if not empty assertTrue(added > 0 ? !bitmap.isEmpty() : bitmap.isEmpty()); assertTrue(added > 0 ? !bitset.isEmpty() : bitset.isEmpty()); assertEquals(added, bitmap.getCardinality()); assertEquals(added, bitset.cardinality()); // apply runtime compression or not if (withRunCompression) { bitmap.runOptimize(); bitmap.removeRunCompression(); } // clear and check bitmap, if really empty bitmap.remove(0L, (long) bits); assertEquals(0, bitmap.getCardinality(), "fails with bits: " + bitset); assertTrue(bitmap.isEmpty()); // clear java's bitset bitset.clear(0, bits); assertEquals(0, bitset.cardinality()); assertTrue(bitset.isEmpty()); } } @Test public void testRemovalWithAddedAndRemovedRunOptimization() { // with runlength encoding testRangeRemovalWithRandomBits(true); } @Test public void testRemovalWithoutAddedAndRemovedRunOptimization() { // without runlength encoding testRangeRemovalWithRandomBits(false); } @Test public void testSetRanges() { int N = 256; for (long end = 1; end < N; ++end) { for (long start = 0; start < end; ++start) { RoaringBitmap bs1 = new RoaringBitmap(); for (int k = (int)start; k < end; ++k) { bs1.add(k); } RoaringBitmap bs2 = new RoaringBitmap(); bs2.add(start, end); assertEquals(bs1, bs2); } } } @Test public void testStaticClearRanges() { int N = 16; for (int end = 1; end < N; ++end) { for (int start = 0; start < end; ++start) { RoaringBitmap bs1 = new RoaringBitmap(); bs1.add(0L, (long) N); for (int k = start; k < end; ++k) { bs1.remove(k); } RoaringBitmap bs2 = new RoaringBitmap(); bs2 = RoaringBitmap.add(bs2, 0L, (long) N); bs2 = RoaringBitmap.remove(bs2, (long) start, (long) end); assertEquals(bs1, bs2); } } } @Test public void testStaticSetRanges() { int N = 256; for (int end = 1; end < N; ++end) { for (int start = 0; start < end; ++start) { RoaringBitmap bs1 = new RoaringBitmap(); for (int k = start; k < end; ++k) { bs1.add(k); } RoaringBitmap bs2 = new RoaringBitmap(); bs2 = RoaringBitmap.add(bs2, (long) start, (long) end); assertEquals(bs1, bs2); } } } /* nb on 20 April 2016, all unit tests above [then] were switched from * the original int-range functions to the wrapper int-range functions * without test errors. Then all code above switched use longs for * range endpoints, again without test errors. * * Below, check the deprecated versions for undocumented behaviours that * hopefully don't rely on...but might have */ @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedStaticAdd() { RoaringBitmap rb1 = RoaringBitmap.add(new RoaringBitmap(), 300000, 500000); RoaringBitmap rb2 = RoaringBitmap.add(new RoaringBitmap(), 300000L, 500000L); assertEquals(rb1, rb2); rb1 = RoaringBitmap.add( rb1, Integer.MAX_VALUE+300000, Integer.MAX_VALUE+500000); rb2 = RoaringBitmap.add( rb2, Integer.MAX_VALUE+300000L, Integer.MAX_VALUE+500000L); assertEquals(rb1, rb2); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedStaticFlip() { RoaringBitmap rb1 = RoaringBitmap.flip(new RoaringBitmap(), 300000, 500000); RoaringBitmap rb2 = RoaringBitmap.flip(new RoaringBitmap(), 300000L, 500000L); assertEquals(rb1, rb2); rb1 = RoaringBitmap.flip(rb1, Integer.MAX_VALUE+300000, Integer.MAX_VALUE+500000); rb2 = RoaringBitmap.flip(rb2, Integer.MAX_VALUE+300000L, Integer.MAX_VALUE+500000L); assertEquals(rb1, rb2); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedMemberFlip() { RoaringBitmap rb1 = new RoaringBitmap(); rb1.flip(300000, 500000); RoaringBitmap rb2 = new RoaringBitmap(); rb2.flip(300000L, 500000L); assertEquals(rb1, rb2); rb1.flip(Integer.MAX_VALUE+300000, Integer.MAX_VALUE+500000); rb2.flip(Integer.MAX_VALUE+300000L, Integer.MAX_VALUE+500000L); assertEquals(rb1, rb2); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedStaticRemove() { RoaringBitmap rb1 = RoaringBitmap.add(new RoaringBitmap(), 200000L, 400000L); rb1 = RoaringBitmap.remove(rb1, 300000, 500000); RoaringBitmap rb2 = RoaringBitmap.add(new RoaringBitmap(), 200000L, 400000L); rb2 = RoaringBitmap.remove(rb2,300000L, 500000L); assertEquals(rb1, rb2); rb1 = RoaringBitmap.add(rb1, Integer.MAX_VALUE+200000L, Integer.MAX_VALUE+400000L); rb2 = RoaringBitmap.add(rb2, Integer.MAX_VALUE+200000L, Integer.MAX_VALUE+400000L); rb1 = RoaringBitmap.remove(rb1, Integer.MAX_VALUE+300000, Integer.MAX_VALUE+500000); rb2 = RoaringBitmap.remove(rb2, Integer.MAX_VALUE+300000L, Integer.MAX_VALUE+500000L); assertEquals(rb1, rb2); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedAdd() { RoaringBitmap rb1 = new RoaringBitmap(); rb1.add(300000, 500000); RoaringBitmap rb2 = new RoaringBitmap(); rb2.add(300000L, 500000L); assertEquals(rb1, rb2); rb1.add( Integer.MAX_VALUE+300000, Integer.MAX_VALUE+500000); rb2.add( Integer.MAX_VALUE+300000L, Integer.MAX_VALUE+500000L); assertEquals(rb1, rb2); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedRemove() { RoaringBitmap rb1 = new RoaringBitmap(); rb1.add(200000L, 400000L); rb1.remove(300000, 500000); RoaringBitmap rb2 = new RoaringBitmap(); rb2.add(200000L, 400000L); rb2.remove(300000L, 500000L); assertEquals(rb1, rb2); rb1.add(Integer.MAX_VALUE+200000L, Integer.MAX_VALUE+400000L); rb2.add(Integer.MAX_VALUE+200000L, Integer.MAX_VALUE+400000L); rb1.remove(Integer.MAX_VALUE+300000, Integer.MAX_VALUE+500000); rb2.remove(Integer.MAX_VALUE+300000L, Integer.MAX_VALUE+500000L); assertEquals(rb1, rb2); } // the other tests for ranged AND are in TestRoaringBitmap; the // range-with-longs is assumed to be okay and only lightly checked here @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedIteratorAnd() { RoaringBitmap rb1 = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); List<RoaringBitmap> list = new ArrayList<>(); list.add(rb1); list.add(rb2); rb1.add(200000L, 400000L); // two normal positive ranges rb2.add(300000L, 500000L); // full overlap is on 300000 to 399999 RoaringBitmap result = RoaringBitmap.and(list.iterator(), 350000L, 450000L); RoaringBitmap resultInt = RoaringBitmap.and(list.iterator(), 350000, 450000); assertEquals(result, resultInt); assertEquals(50000, result.getCardinality()); // empty ranges get empty result resultInt = RoaringBitmap.and(list.iterator(), 300000, 200000); result = RoaringBitmap.and(list.iterator(), 300000L, 200000L); assertEquals(result, resultInt); assertEquals(0, resultInt.getCardinality()); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedIteratorOr() { RoaringBitmap rb1 = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); List<RoaringBitmap> list = new ArrayList<>(); list.add(rb1); list.add(rb2); rb1.add(200000L, 400000L); // two normal positive ranges rb2.add(300000L, 500000L); // full union is 200000 to 499999 RoaringBitmap result = RoaringBitmap.or(list.iterator(), 250000L, 550000L); RoaringBitmap resultInt = RoaringBitmap.or(list.iterator(), 250000, 550000); assertEquals(result, resultInt); assertEquals(250000, result.getCardinality()); // empty ranges get empty result resultInt = RoaringBitmap.or(list.iterator(), 300000, 200000); result = RoaringBitmap.or(list.iterator(), 300000L, 200000L); assertEquals(result, resultInt); assertEquals(0, resultInt.getCardinality()); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedIteratorAndNot() { RoaringBitmap rb1 = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); List<RoaringBitmap> list = new ArrayList<>(); list.add(rb1); list.add(rb2); rb1.add(200000L, 400000L); // two normal positive ranges rb2.add(300000L, 500000L); // full andNOToverlap is on 200000 to 299999 RoaringBitmap result = RoaringBitmap.andNot(rb1, rb2, 250000L, 450000L); RoaringBitmap resultInt = RoaringBitmap.andNot(rb1, rb2, 250000, 450000); assertEquals(result, resultInt); assertEquals(50000, result.getCardinality()); // empty ranges get empty result resultInt = RoaringBitmap.andNot(rb1, rb2, 300000, 200000); result = RoaringBitmap.andNot(rb1, rb2, 300000L, 200000L); assertEquals(result, resultInt); assertEquals(0, resultInt.getCardinality()); } @Test @SuppressWarnings( "deprecation" ) public void testDeprecatedIteratorXor() { RoaringBitmap rb1 = new RoaringBitmap(); RoaringBitmap rb2 = new RoaringBitmap(); List<RoaringBitmap> list = new ArrayList<>(); list.add(rb1); list.add(rb2); rb1.add(200000L, 400000L); // two normal positive ranges rb2.add(300000L, 500000L); // full XOR is 200000 to 299999, 400000-4999999 RoaringBitmap result = RoaringBitmap.xor(list.iterator(), 250000L, 450000L); RoaringBitmap resultInt = RoaringBitmap.xor(list.iterator(), 250000, 450000); assertEquals(result, resultInt); assertEquals(100000, result.getCardinality()); // empty ranges get empty result resultInt = RoaringBitmap.xor(list.iterator(), 300000, 200000); result = RoaringBitmap.xor(list.iterator(), 300000L, 200000L); assertEquals(result, resultInt); assertEquals(0, resultInt.getCardinality()); } }
/* * Copyright 2004 and onwards Sean Owen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ziplet.filter.compression; import com.github.ziplet.filter.compression.statistics.CompressingFilterStats; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; 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.regex.Pattern; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.InflaterInputStream; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; /** * <p>Implementations of this abstract class can add compression of a particular type to a given * {@link OutputStream}. They each return a {@link CompressingOutputStream}, which is just a thin * wrapper on top of an {@link OutputStream} that adds the ability to "finish" a stream (see {@link * CompressingOutputStream}).</p> * * <p>This class contains implementations based on several popular compression algorithms, such as * gzip. For example, the gzip implementation can decorate an {@link OutputStream} using an instance * of {@link GZIPOutputStream} and in that way add gzip compression to the stream.</p> * * @author Sean Owen */ abstract class CompressingStreamFactory { /** * "No encoding" content type: "identity". */ static final String NO_ENCODING = "identity"; /** * Implementation based on {@link GZIPOutputStream} and {@link GZIPInputStream}. */ private static final CompressingStreamFactory GZIP_CSF = new GZIPCompressingStreamFactory(); /** * Implementation based on {@link ZipOutputStream} and {@link ZipInputStream}. */ private static final CompressingStreamFactory ZIP_CSF = new ZipCompressingStreamFactory(); /** * Implementation based on {@link DeflaterOutputStream}. */ private static final CompressingStreamFactory DEFLATE_CSF = new DeflateCompressingStreamFactory(); private static final String GZIP_ENCODING = "gzip"; private static final String X_GZIP_ENCODING = "x-gzip"; private static final String DEFLATE_ENCODING = "deflate"; private static final String COMPRESS_ENCODING = "compress"; private static final String X_COMPRESS_ENCODING = "x-compress"; static final String[] ALL_COMPRESSION_ENCODINGS = { GZIP_ENCODING, DEFLATE_ENCODING, COMPRESS_ENCODING, X_GZIP_ENCODING, X_COMPRESS_ENCODING }; /** * "Any encoding" content type: the "*" wildcard. */ private static final String ANY_ENCODING = "*"; /** * Ordered list of preferred encodings, from most to least preferred */ private static final List<String> supportedEncodings; /** * Cache mapping previously seen "Accept-Encoding" header Strings to an appropriate instance of * {@link CompressingStreamFactory}. */ private static final Map<String, String> bestEncodingCache = Collections.synchronizedMap(new HashMap<String, String>(101)); /** * Maps content type String to appropriate implementation of {@link CompressingStreamFactory}. */ private static final Map<String, CompressingStreamFactory> factoryMap; private static final Pattern COMMA = Pattern.compile(","); static { List<String> temp = new ArrayList<String>(6); temp.add(GZIP_ENCODING); temp.add(DEFLATE_ENCODING); temp.add(COMPRESS_ENCODING); temp.add(X_GZIP_ENCODING); temp.add(X_COMPRESS_ENCODING); temp.add(NO_ENCODING); supportedEncodings = Collections.unmodifiableList(temp); } static { Map<String, CompressingStreamFactory> temp = new HashMap<String, CompressingStreamFactory>( 11); temp.put(GZIP_ENCODING, GZIP_CSF); temp.put(X_GZIP_ENCODING, GZIP_CSF); temp.put(COMPRESS_ENCODING, ZIP_CSF); temp.put(X_COMPRESS_ENCODING, ZIP_CSF); temp.put(DEFLATE_ENCODING, DEFLATE_CSF); factoryMap = Collections.unmodifiableMap(temp); } private static OutputStream maybeWrapStatsOutputStream(OutputStream outputStream, CompressingFilterContext context, StatsField field) { assert outputStream != null; OutputStream result; CompressingFilterStats stats = context.getStats(); result = new StatsOutputStream(outputStream, stats, field); return result; } private static InputStream maybeWrapStatsInputStream(InputStream inputStream, CompressingFilterContext context, StatsField field) { assert inputStream != null; InputStream result; CompressingFilterStats stats = context.getStats(); result = new StatsInputStream(inputStream, stats, field); return result; } private static boolean isSupportedResponseContentEncoding(String contentEncoding) { return NO_ENCODING.equals(contentEncoding) || factoryMap.containsKey(contentEncoding); } static boolean isSupportedRequestContentEncoding(String contentEncoding) { return NO_ENCODING.equals(contentEncoding) || factoryMap.containsKey(contentEncoding); } /** * Returns the instance associated to the given content encoding. * * @param contentEncoding content encoding (e.g. "gzip") * @return instance for content encoding */ static CompressingStreamFactory getFactoryForContentEncoding(String contentEncoding) { assert factoryMap.containsKey(contentEncoding); return factoryMap.get(contentEncoding); } /** * Determines best content encoding for the response, based on the request -- in particular, * based on its "Accept-Encoding" header. * * @param httpRequest request * @return best content encoding */ static String getBestContentEncoding(HttpServletRequest httpRequest) { String forcedEncoding = (String) httpRequest .getAttribute(CompressingFilter.FORCE_ENCODING_KEY); String bestEncoding; if (forcedEncoding != null) { bestEncoding = forcedEncoding; } else { String acceptEncodingHeader = httpRequest.getHeader( CompressingHttpServletResponse.ACCEPT_ENCODING_HEADER); if (acceptEncodingHeader == null) { bestEncoding = NO_ENCODING; } else { bestEncoding = bestEncodingCache.get(acceptEncodingHeader); if (bestEncoding == null) { // No cached value; must parse header to determine best encoding // I don't synchronize on bestEncodingCache; it's not worth it to avoid the rare case where // two thread get in here and both parse the header. It's only a tiny bit of extra work, and // avoids the synchronization overhead. if (acceptEncodingHeader.indexOf((int) ',') >= 0) { // multiple encodings are accepted bestEncoding = selectBestEncoding(acceptEncodingHeader); } else { // one encoding is accepted bestEncoding = parseBestEncoding(acceptEncodingHeader); } bestEncodingCache.put(acceptEncodingHeader, bestEncoding); } } } // User-specified encoding might not be supported if (!isSupportedResponseContentEncoding(bestEncoding)) { bestEncoding = NO_ENCODING; } return bestEncoding; } private static String parseBestEncoding(String acceptEncodingHeader) { ContentEncodingQ contentEncodingQ = parseContentEncodingQ(acceptEncodingHeader); String contentEncoding = contentEncodingQ.getContentEncoding(); if (contentEncodingQ.getQ() > 0.0) { if (ANY_ENCODING.equals(contentEncoding)) { return supportedEncodings.get(0); } else if (supportedEncodings.contains(contentEncoding)) { return contentEncoding; } } return NO_ENCODING; } private static String selectBestEncoding(String acceptEncodingHeader) { // multiple encodings are accepted; determine best one Collection<String> bestEncodings = new HashSet<String>(3); double bestQ = 0.0; Collection<String> unacceptableEncodings = new HashSet<String>(3); boolean willAcceptAnything = false; for (String token : COMMA.split(acceptEncodingHeader)) { ContentEncodingQ contentEncodingQ = parseContentEncodingQ(token); String contentEncoding = contentEncodingQ.getContentEncoding(); double q = contentEncodingQ.getQ(); if (ANY_ENCODING.equals(contentEncoding)) { willAcceptAnything = q > 0.0; } else if (supportedEncodings.contains(contentEncoding)) { if (q > 0.0) { if (q == bestQ) { bestEncodings.add(contentEncoding); } else if (q > bestQ) { bestQ = q; bestEncodings.clear(); bestEncodings.add(contentEncoding); } } else { unacceptableEncodings.add(contentEncoding); } } } if (bestEncodings.isEmpty()) { // nothing was acceptable to us if (willAcceptAnything) { if (unacceptableEncodings.isEmpty()) { return supportedEncodings.get(0); } else { for (String encoding : supportedEncodings) { if (!unacceptableEncodings.contains(encoding)) { return encoding; } } } } } else { for (String encoding : supportedEncodings) { if (bestEncodings.contains(encoding)) { return encoding; } } } return NO_ENCODING; } private static ContentEncodingQ parseContentEncodingQ(String contentEncodingString) { double q = 1.0; int qvalueStartIndex = contentEncodingString.indexOf((int) ';'); String contentEncoding; if (qvalueStartIndex >= 0) { contentEncoding = contentEncodingString.substring(0, qvalueStartIndex).trim(); String qvalueString = contentEncodingString.substring(qvalueStartIndex + 1).trim(); if (qvalueString.startsWith("q=")) { try { q = Double.parseDouble(qvalueString.substring(2)); } catch (NumberFormatException nfe) { // That's bad -- browser sent an invalid number. All we can do is ignore it, and // pretend that no q value was specified, so that it effectively defaults to 1.0 } } } else { contentEncoding = contentEncodingString.trim(); } return new ContentEncodingQ(contentEncoding, q); } abstract CompressingOutputStream getCompressingStream(OutputStream servletOutputStream, CompressingFilterContext context) throws IOException; abstract CompressingInputStream getCompressingStream(InputStream servletInputStream, CompressingFilterContext context) throws IOException; private static final class ContentEncodingQ { private final String contentEncoding; private final double q; private ContentEncodingQ(String contentEncoding, double q) { assert contentEncoding != null && contentEncoding.length() > 0; this.contentEncoding = contentEncoding; this.q = q; } String getContentEncoding() { return contentEncoding; } double getQ() { return q; } @Override public String toString() { return contentEncoding + ";q=" + q; } } private static class GZIPCompressingStreamFactory extends CompressingStreamFactory { @Override CompressingOutputStream getCompressingStream(final OutputStream outputStream, final CompressingFilterContext context) throws IOException { return new CompressingOutputStream() { private final DeflaterOutputStream gzipOutputStream = new LevelGZIPOutputStream( CompressingStreamFactory.maybeWrapStatsOutputStream( outputStream, context, StatsField.RESPONSE_COMPRESSED_BYTES), context.getCompressionLevel()); private final OutputStream statsOutputStream = CompressingStreamFactory.maybeWrapStatsOutputStream( gzipOutputStream, context, StatsField.RESPONSE_INPUT_BYTES); public OutputStream getCompressingOutputStream() { return statsOutputStream; } public void finish() throws IOException { gzipOutputStream.finish(); } }; } @Override CompressingInputStream getCompressingStream(final InputStream inputStream, final CompressingFilterContext context) { return new CompressingInputStream() { public InputStream getCompressingInputStream() throws IOException { return CompressingStreamFactory.maybeWrapStatsInputStream( new GZIPInputStream( CompressingStreamFactory.maybeWrapStatsInputStream( inputStream, context, StatsField.REQUEST_COMPRESSED_BYTES)), context, StatsField.REQUEST_INPUT_BYTES); } }; } private static class LevelGZIPOutputStream extends GZIPOutputStream { public LevelGZIPOutputStream(OutputStream out, int compressionLevel) throws IOException { super(out); def.setLevel(compressionLevel); } } } private static class ZipCompressingStreamFactory extends CompressingStreamFactory { @Override CompressingOutputStream getCompressingStream(final OutputStream outputStream, final CompressingFilterContext context) { return new CompressingOutputStream() { private final DeflaterOutputStream zipOutputStream = new ZipOutputStream( CompressingStreamFactory.maybeWrapStatsOutputStream( outputStream, context, StatsField.RESPONSE_COMPRESSED_BYTES)); private final OutputStream statsOutputStream = CompressingStreamFactory.maybeWrapStatsOutputStream( zipOutputStream, context, StatsField.RESPONSE_INPUT_BYTES); public OutputStream getCompressingOutputStream() { return statsOutputStream; } public void finish() throws IOException { zipOutputStream.finish(); } }; } @Override CompressingInputStream getCompressingStream(final InputStream inputStream, final CompressingFilterContext context) { return new CompressingInputStream() { public InputStream getCompressingInputStream() { return CompressingStreamFactory.maybeWrapStatsInputStream( new ZipInputStream( CompressingStreamFactory.maybeWrapStatsInputStream( inputStream, context, StatsField.REQUEST_COMPRESSED_BYTES)), context, StatsField.REQUEST_INPUT_BYTES); } }; } } private static class DeflateCompressingStreamFactory extends CompressingStreamFactory { @Override CompressingOutputStream getCompressingStream(final OutputStream outputStream, final CompressingFilterContext context) { return new CompressingOutputStream() { private final DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream( CompressingStreamFactory.maybeWrapStatsOutputStream( outputStream, context, StatsField.RESPONSE_COMPRESSED_BYTES), new Deflater(context.getCompressionLevel())); private final OutputStream statsOutputStream = CompressingStreamFactory.maybeWrapStatsOutputStream( deflaterOutputStream, context, StatsField.RESPONSE_INPUT_BYTES); public OutputStream getCompressingOutputStream() { return statsOutputStream; } public void finish() throws IOException { deflaterOutputStream.finish(); } }; } @Override CompressingInputStream getCompressingStream(final InputStream inputStream, final CompressingFilterContext context) { return new CompressingInputStream() { public InputStream getCompressingInputStream() { return CompressingStreamFactory.maybeWrapStatsInputStream( new InflaterInputStream( CompressingStreamFactory.maybeWrapStatsInputStream( inputStream, context, StatsField.REQUEST_COMPRESSED_BYTES)), context, StatsField.REQUEST_INPUT_BYTES); } }; } } }
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.android.designer.model.layout.grid; import com.android.tools.idea.designer.ResizeOperation; import com.intellij.android.designer.designSurface.TreeDropToOperation; import com.intellij.android.designer.designSurface.graphics.DrawingStyle; import com.intellij.android.designer.designSurface.layout.GridLayoutOperation; import com.intellij.android.designer.designSurface.layout.actions.GridLayoutSpanOperation; import com.intellij.android.designer.designSurface.layout.actions.LayoutSpanOperation; import com.intellij.android.designer.designSurface.layout.caption.GridHorizontalCaptionOperation; import com.intellij.android.designer.designSurface.layout.caption.GridVerticalCaptionOperation; import com.intellij.android.designer.designSurface.layout.grid.GridDecorator; import com.intellij.android.designer.designSurface.layout.grid.GridSelectionDecorator; import com.intellij.android.designer.model.RadViewComponent; import com.intellij.android.designer.model.RadViewLayout; import com.intellij.android.designer.model.RadViewLayoutWithData; import com.intellij.android.designer.model.grid.GridInfo; import com.intellij.android.designer.model.layout.actions.AllGravityAction; import com.intellij.android.designer.model.layout.actions.OrientationAction; import com.intellij.designer.componentTree.TreeEditOperation; import com.intellij.designer.designSurface.*; import com.intellij.designer.model.RadComponent; import com.intellij.designer.model.RadLayout; import com.intellij.openapi.actionSystem.DefaultActionGroup; import org.jetbrains.annotations.NotNull; import com.intellij.android.designer.designSurface.RootView; import java.awt.*; import java.util.ArrayList; import java.util.List; /** * @author Alexander Lobas */ public class RadGridLayout extends RadViewLayoutWithData implements ILayoutDecorator, ICaption, ICaptionDecorator { private static final String[] LAYOUT_PARAMS = {"GridLayout_Layout", "ViewGroup_MarginLayout"}; private GridDecorator myGridDecorator; private GridSelectionDecorator mySelectionDecorator; @NotNull @Override public String[] getLayoutParams() { return LAYOUT_PARAMS; } @Override public EditOperation processChildOperation(OperationContext context) { if (context.isCreate() || context.isPaste() || context.isAdd() || context.isMove()) { if (context.isTree()) { if (TreeEditOperation.isTarget(myContainer, context)) { return new TreeDropToOperation(myContainer, context); } return null; } return new GridLayoutOperation(myContainer, context); } if (context.is(ResizeOperation.TYPE)) { return new ResizeOperation(context); } if (context.is(LayoutSpanOperation.TYPE)) { return new GridLayoutSpanOperation(context, mySelectionDecorator); } return null; } private StaticDecorator getGridDecorator() { if (myGridDecorator == null) { myGridDecorator = new GridDecorator(myContainer); } return myGridDecorator; } @Override public void addStaticDecorators(List<StaticDecorator> decorators, List<RadComponent> selection) { if (selection.contains(myContainer)) { if (!(myContainer.getParent().getLayout() instanceof ILayoutDecorator)) { decorators.add(getGridDecorator()); } } else { for (RadComponent component : selection) { if (component.getParent() == myContainer) { decorators.add(getGridDecorator()); return; } } super.addStaticDecorators(decorators, selection); } } @Override public ComponentDecorator getChildSelectionDecorator(RadComponent component, List<RadComponent> selection) { if (mySelectionDecorator == null) { mySelectionDecorator = new GridSelectionDecorator(DrawingStyle.SELECTION) { @Override public Rectangle getCellBounds(Component layer, RadComponent component) { try { RadGridLayoutComponent parent = (RadGridLayoutComponent)component.getParent(); GridInfo gridInfo = parent.getGridInfo(); Rectangle cellInfo = RadGridLayoutComponent.getCellInfo(component); return calculateBounds(layer, gridInfo, parent, component, cellInfo.y, cellInfo.x, cellInfo.height, cellInfo.width); } catch (Throwable e) { return new Rectangle(); } } }; } mySelectionDecorator.clear(); if (selection.size() == 1) { GridLayoutSpanOperation.points(mySelectionDecorator); ResizeOperation.addResizePoints(mySelectionDecorator, (RadViewComponent)selection.get(0)); } else { ResizeOperation.addResizePoints(mySelectionDecorator); } return mySelectionDecorator; } ////////////////////////////////////////////////////////////////////////////////////////// // // Actions // ////////////////////////////////////////////////////////////////////////////////////////// @Override public void addContainerSelectionActions(DesignerEditorPanel designer, DefaultActionGroup actionGroup, List<? extends RadViewComponent> selection) { super.addContainerSelectionActions(designer, actionGroup, selection); actionGroup.add(new OrientationAction(designer, (RadViewComponent)myContainer, true)); actionGroup.add(new AllGravityAction(designer, selection)); } ////////////////////////////////////////////////////////////////////////////////////////// // // Caption // ////////////////////////////////////////////////////////////////////////////////////////// @Override public ICaption getCaption(RadComponent component) { if (myContainer == component && myContainer.getParent().getLayout() instanceof ICaptionDecorator) { return null; } if (myContainer.getChildren().isEmpty()) { return null; } return this; } /** * Returns the list of components to be displayed in the caption area (editor borders). * @param mainArea The {@link EditableArea} instance where the caption is being displayed. * @param horizontal true if this is for the horizontal border or false for the vertical. */ @NotNull @Override public List<RadComponent> getCaptionChildren(EditableArea mainArea, boolean horizontal) { RadGridLayoutComponent container = getGridComponent(); GridInfo gridInfo = container.getGridInfo(); List<RadComponent> components = new ArrayList<RadComponent>(); RootView nativeComponent = (RootView)((RadViewComponent)container.getRoot()).getNativeComponent(); // If the image has a frame, we need to offset the hints to make them match with the device image. boolean hasFrame = nativeComponent.getRenderedImage() != null && nativeComponent.getRenderedImage().getImageBounds() != null; if (horizontal) { int[] lines = gridInfo.vLines; boolean[] emptyColumns = gridInfo.emptyColumns; int offset = hasFrame ? (int)(nativeComponent.getShiftX() / nativeComponent.getScale()) : 0; for (int i = 0; i < lines.length - 1; i++) { components.add(new RadCaptionGridColumn(mainArea, container, i, offset + lines[i], lines[i + 1] - lines[i], emptyColumns[i])); } } else { int[] lines = gridInfo.hLines; boolean[] emptyRows = gridInfo.emptyRows; int offset = hasFrame ? (int)(nativeComponent.getShiftY() / nativeComponent.getScale()) : 0; for (int i = 0; i < lines.length - 1; i++) { components.add(new RadCaptionGridRow(mainArea, container, i, offset + lines[i], lines[i + 1] - lines[i], emptyRows[i])); } } return components; } private RadGridLayoutComponent getGridComponent() { return (RadGridLayoutComponent)myContainer; } private RadLayout myCaptionColumnLayout; private RadLayout myCaptionRowLayout; @NotNull @Override public RadLayout getCaptionLayout(final EditableArea mainArea, boolean horizontal) { if (horizontal) { if (myCaptionColumnLayout == null) { myCaptionColumnLayout = new RadViewLayout() { @Override public EditOperation processChildOperation(OperationContext context) { if (context.isMove()) { return new GridHorizontalCaptionOperation(getGridComponent(), myContainer, context, mainArea); } return null; } }; } return myCaptionColumnLayout; } if (myCaptionRowLayout == null) { myCaptionRowLayout = new RadViewLayout() { @Override public EditOperation processChildOperation(OperationContext context) { if (context.isMove()) { return new GridVerticalCaptionOperation(getGridComponent(), myContainer, context, mainArea); } return null; } }; } return myCaptionRowLayout; } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.rename.inplace; import com.intellij.lang.Language; import com.intellij.lang.LanguageExtension; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.command.impl.FinishMarkAction; import com.intellij.openapi.command.impl.StartMarkAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.listeners.RefactoringElementListener; import com.intellij.refactoring.listeners.RefactoringEventData; import com.intellij.refactoring.listeners.RefactoringEventListener; import com.intellij.refactoring.rename.*; import com.intellij.refactoring.rename.naming.AutomaticRenamer; import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.TextOccurrencesUtil; import com.intellij.usageView.UsageInfo; import com.intellij.util.PairProcessor; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; /** * @author ven */ public class VariableInplaceRenamer extends InplaceRefactoring { public static final LanguageExtension<ResolveSnapshotProvider> INSTANCE = new LanguageExtension<ResolveSnapshotProvider>( "com.intellij.rename.inplace.resolveSnapshotProvider" ); private ResolveSnapshotProvider.ResolveSnapshot mySnapshot; private TextRange mySelectedRange; protected Language myLanguage; public VariableInplaceRenamer(@NotNull PsiNamedElement elementToRename, Editor editor) { this(elementToRename, editor, elementToRename.getProject()); } public VariableInplaceRenamer(PsiNamedElement elementToRename, Editor editor, Project project) { this(elementToRename, editor, project, elementToRename != null ? elementToRename.getName() : null, elementToRename != null ? elementToRename.getName() : null); } public VariableInplaceRenamer(PsiNamedElement elementToRename, Editor editor, Project project, final String initialName, final String oldName) { super(editor, elementToRename, project, initialName, oldName); } @Override protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) { return super.startsOnTheSameElement(handler, element) && handler instanceof VariableInplaceRenameHandler; } public boolean performInplaceRename() { return performInplaceRefactoring(null); } @Override protected void collectAdditionalElementsToRename(final List<Pair<PsiElement, TextRange>> stringUsages) { final String stringToSearch = myElementToRename.getName(); final PsiFile currentFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument()); if (stringToSearch != null) { TextOccurrencesUtil .processUsagesInStringsAndComments(myElementToRename, stringToSearch, true, new PairProcessor<PsiElement, TextRange>() { @Override public boolean process(PsiElement psiElement, TextRange textRange) { if (psiElement.getContainingFile() == currentFile) { stringUsages.add(Pair.create(psiElement, textRange)); } return true; } }); } } @Override protected boolean buildTemplateAndStart(final Collection<PsiReference> refs, Collection<Pair<PsiElement, TextRange>> stringUsages, final PsiElement scope, final PsiFile containingFile) { if (appendAdditionalElement(refs, stringUsages)) { return super.buildTemplateAndStart(refs, stringUsages, scope, containingFile); } else { final RenameChooser renameChooser = new RenameChooser(myEditor) { @Override protected void runRenameTemplate(Collection<Pair<PsiElement, TextRange>> stringUsages) { VariableInplaceRenamer.super.buildTemplateAndStart(refs, stringUsages, scope, containingFile); } }; renameChooser.showChooser(refs, stringUsages); } return true; } protected boolean appendAdditionalElement(Collection<PsiReference> refs, Collection<Pair<PsiElement, TextRange>> stringUsages) { return stringUsages.isEmpty() || StartMarkAction.canStart(myProject) != null; } protected boolean shouldCreateSnapshot() { return true; } protected String getRefactoringId() { return "refactoring.rename"; } @Override protected void beforeTemplateStart() { super.beforeTemplateStart(); myLanguage = myScope.getLanguage(); if (shouldCreateSnapshot()) { final ResolveSnapshotProvider resolveSnapshotProvider = INSTANCE.forLanguage(myLanguage); mySnapshot = resolveSnapshotProvider != null ? resolveSnapshotProvider.createSnapshot(myScope) : null; } final SelectionModel selectionModel = myEditor.getSelectionModel(); mySelectedRange = selectionModel.hasSelection() ? new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) : null; } @Override protected void restoreSelection() { if (mySelectedRange != null) { myEditor.getSelectionModel().setSelection(mySelectedRange.getStartOffset(), mySelectedRange.getEndOffset()); } else if (!shouldSelectAll()) { myEditor.getSelectionModel().removeSelection(); } } @Override protected int restoreCaretOffset(int offset) { if (myCaretRangeMarker.isValid()) { if (myCaretRangeMarker.getStartOffset() <= offset && myCaretRangeMarker.getEndOffset() >= offset) { return offset; } return myCaretRangeMarker.getEndOffset(); } return offset; } @Override protected boolean shouldSelectAll() { if (myEditor.getSettings().isPreselectRename()) return true; final Boolean selectAll = myEditor.getUserData(RenameHandlerRegistry.SELECT_ALL); return selectAll != null && selectAll.booleanValue(); } protected VariableInplaceRenamer createInplaceRenamerToRestart(PsiNamedElement variable, Editor editor, String initialName) { return new VariableInplaceRenamer(variable, editor, myProject, initialName, myOldName); } protected void performOnInvalidIdentifier(final String newName, final LinkedHashSet<String> nameSuggestions) { final PsiNamedElement variable = getVariable(); if (variable != null) { final int offset = variable.getTextOffset(); restoreCaretOffset(offset); JBPopupFactory.getInstance() .createConfirmation("Inserted identifier is not valid", "Continue editing", "Cancel", new Runnable() { @Override public void run() { createInplaceRenamerToRestart(variable, myEditor, newName).performInplaceRefactoring(nameSuggestions); } }, 0).showInBestPositionFor(myEditor); } } protected void renameSynthetic(String newName) { } protected void performRefactoringRename(final String newName, final StartMarkAction markAction) { final String refactoringId = getRefactoringId(); try { PsiNamedElement elementToRename = getVariable(); if (refactoringId != null) { final RefactoringEventData beforeData = new RefactoringEventData(); beforeData.addElement(elementToRename); beforeData.addStringProperties(myOldName); myProject.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, beforeData); } if (!isIdentifier(newName, myLanguage)) { return; } if (elementToRename != null) { new WriteCommandAction(myProject, getCommandName()) { @Override protected void run(Result result) throws Throwable { renameSynthetic(newName); } }.execute(); } for (AutomaticRenamerFactory renamerFactory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) { if (elementToRename != null && renamerFactory.isApplicable(elementToRename)) { final List<UsageInfo> usages = new ArrayList<UsageInfo>(); final AutomaticRenamer renamer = renamerFactory.createRenamer(elementToRename, newName, new ArrayList<UsageInfo>()); if (renamer.hasAnythingToRename()) { if (!ApplicationManager.getApplication().isUnitTestMode()) { final AutomaticRenamingDialog renamingDialog = new AutomaticRenamingDialog(myProject, renamer); if (!renamingDialog.showAndGet()) { return; } } final Runnable runnable = new Runnable() { @Override public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { renamer.findUsages(usages, false, false); } }); } }; if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously(runnable, RefactoringBundle.message("searching.for.variables"), true, myProject)) { return; } if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, PsiUtilCore.toPsiElementArray(renamer.getElements()))) return; final Runnable performAutomaticRename = new Runnable() { @Override public void run() { CommandProcessor.getInstance().markCurrentCommandAsGlobal(myProject); final UsageInfo[] usageInfos = usages.toArray(new UsageInfo[usages.size()]); final MultiMap<PsiElement, UsageInfo> classified = RenameProcessor.classifyUsages(renamer.getElements(), usageInfos); for (final PsiNamedElement element : renamer.getElements()) { final String newElementName = renamer.getNewName(element); if (newElementName != null) { final Collection<UsageInfo> infos = classified.get(element); RenameUtil.doRename(element, newElementName, infos.toArray(new UsageInfo[infos.size()]), myProject, RefactoringElementListener.DEAF); } } } }; final WriteCommandAction writeCommandAction = new WriteCommandAction(myProject, getCommandName()) { @Override protected void run(Result result) throws Throwable { performAutomaticRename.run(); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { writeCommandAction.execute(); } else { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { writeCommandAction.execute(); } }); } } } } } finally { if (refactoringId != null) { final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(getVariable()); afterData.addStringProperties(newName); myProject.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, afterData); } try { ((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater(); } finally { FinishMarkAction.finish(myProject, myEditor, markAction); } } } @Override protected String getCommandName() { return RefactoringBundle.message("renaming.command.name", myInitialName); } @Override protected boolean performRefactoring() { boolean bind = false; if (myInsertedName != null) { final CommandProcessor commandProcessor = CommandProcessor.getInstance(); if (commandProcessor.getCurrentCommand() != null && getVariable() != null) { commandProcessor.setCurrentCommandName(getCommandName()); } bind = true; if (!isIdentifier(myInsertedName, myLanguage)) { performOnInvalidIdentifier(myInsertedName, myNameSuggestions); } else { if (mySnapshot != null) { if (isIdentifier(myInsertedName, myLanguage)) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { mySnapshot.apply(myInsertedName); } }); } } } performRefactoringRename(myInsertedName, myMarkAction); } return bind; } @Override public void finish(boolean success) { super.finish(success); if (success) { revertStateOnFinish(); } else { ((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater(); } } protected void revertStateOnFinish() { if (myInsertedName == null || !isIdentifier(myInsertedName, myLanguage)) { revertState(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.partition; import static org.junit.Assert.*; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.schema.ColumnMetadata; import org.apache.cassandra.schema.TableMetadata; import org.apache.cassandra.cql3.ColumnIdentifier; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.ColumnFilter; import org.apache.cassandra.db.marshal.AsciiType; import org.apache.cassandra.db.partitions.AbstractBTreePartition; import org.apache.cassandra.db.partitions.ImmutableBTreePartition; import org.apache.cassandra.db.partitions.Partition; import org.apache.cassandra.db.rows.*; import org.apache.cassandra.db.rows.Row.Deletion; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.SearchIterator; public class PartitionImplementationTest { private static final String KEYSPACE = "PartitionImplementationTest"; private static final String CF = "Standard"; private static final int ENTRIES = 250; private static final int TESTS = 1000; private static final int KEY_RANGE = ENTRIES * 5; private static final int TIMESTAMP = KEY_RANGE + 1; private static TableMetadata metadata; private Random rand = new Random(2); @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); metadata = TableMetadata.builder(KEYSPACE, CF) .addPartitionKeyColumn("pk", AsciiType.instance) .addClusteringColumn("ck", AsciiType.instance) .addRegularColumn("col", AsciiType.instance) .addStaticColumn("static_col", AsciiType.instance) .build(); SchemaLoader.createKeyspace(KEYSPACE, KeyspaceParams.simple(1), metadata); } private List<Row> generateRows() { List<Row> content = new ArrayList<>(); Set<Integer> keysUsed = new HashSet<>(); for (int i = 0; i < ENTRIES; ++i) { int rk; do { rk = rand.nextInt(KEY_RANGE); } while (!keysUsed.add(rk)); content.add(makeRow(clustering(rk), "Col" + rk)); } return content; // not sorted } Row makeRow(Clustering clustering, String colValue) { ColumnMetadata defCol = metadata.getColumn(new ColumnIdentifier("col", true)); Row.Builder row = BTreeRow.unsortedBuilder(TIMESTAMP); row.newRow(clustering); row.addCell(BufferCell.live(defCol, TIMESTAMP, ByteBufferUtil.bytes(colValue))); return row.build(); } Row makeStaticRow() { ColumnMetadata defCol = metadata.getColumn(new ColumnIdentifier("static_col", true)); Row.Builder row = BTreeRow.unsortedBuilder(TIMESTAMP); row.newRow(Clustering.STATIC_CLUSTERING); row.addCell(BufferCell.live(defCol, TIMESTAMP, ByteBufferUtil.bytes("static value"))); return row.build(); } private List<Unfiltered> generateMarkersOnly() { return addMarkers(new ArrayList<>()); } private List<Unfiltered> generateUnfiltereds() { List<Unfiltered> content = new ArrayList<>(generateRows()); return addMarkers(content); } List<Unfiltered> addMarkers(List<Unfiltered> content) { List<RangeTombstoneMarker> markers = new ArrayList<>(); Set<Integer> delTimes = new HashSet<>(); for (int i = 0; i < ENTRIES / 10; ++i) { int delTime; do { delTime = rand.nextInt(KEY_RANGE); } while (!delTimes.add(delTime)); int start = rand.nextInt(KEY_RANGE); DeletionTime dt = new DeletionTime(delTime, delTime); RangeTombstoneMarker open = RangeTombstoneBoundMarker.inclusiveOpen(false, clustering(start).getRawValues(), dt); int end = start + rand.nextInt((KEY_RANGE - start) / 4 + 1); RangeTombstoneMarker close = RangeTombstoneBoundMarker.inclusiveClose(false, clustering(end).getRawValues(), dt); markers.add(open); markers.add(close); } markers.sort(metadata.comparator); RangeTombstoneMarker toAdd = null; Set<DeletionTime> open = new HashSet<>(); DeletionTime current = DeletionTime.LIVE; for (RangeTombstoneMarker marker : markers) { if (marker.isOpen(false)) { DeletionTime delTime = marker.openDeletionTime(false); open.add(delTime); if (delTime.supersedes(current)) { if (toAdd != null) { if (metadata.comparator.compare(toAdd, marker) != 0) content.add(toAdd); else { // gotta join current = toAdd.isClose(false) ? toAdd.closeDeletionTime(false) : DeletionTime.LIVE; } } if (current != DeletionTime.LIVE) marker = RangeTombstoneBoundaryMarker.makeBoundary(false, marker.openBound(false).invert(), marker.openBound(false), current, delTime); toAdd = marker; current = delTime; } } else { assert marker.isClose(false); DeletionTime delTime = marker.closeDeletionTime(false); boolean removed = open.remove(delTime); assert removed; if (current.equals(delTime)) { if (toAdd != null) { if (metadata.comparator.compare(toAdd, marker) != 0) content.add(toAdd); else { // gotta join current = toAdd.closeDeletionTime(false); marker = new RangeTombstoneBoundMarker(marker.closeBound(false), current); } } DeletionTime best = open.stream().max(DeletionTime::compareTo).orElse(DeletionTime.LIVE); if (best != DeletionTime.LIVE) marker = RangeTombstoneBoundaryMarker.makeBoundary(false, marker.closeBound(false), marker.closeBound(false).invert(), current, best); toAdd = marker; current = best; } } } content.add(toAdd); assert current == DeletionTime.LIVE; assert open.isEmpty(); return content; } private Clustering clustering(int i) { return metadata.comparator.make(String.format("Row%06d", i)); } private void test(Supplier<Collection<? extends Unfiltered>> content, Row staticRow) { for (int i = 0; i<TESTS; ++i) { try { rand = new Random(i); testIter(content, staticRow); } catch (Throwable t) { throw new AssertionError("Test failed with seed " + i, t); } } } private void testIter(Supplier<Collection<? extends Unfiltered>> contentSupplier, Row staticRow) { NavigableSet<Clusterable> sortedContent = new TreeSet<Clusterable>(metadata.comparator); sortedContent.addAll(contentSupplier.get()); AbstractBTreePartition partition; try (UnfilteredRowIterator iter = new Util.UnfilteredSource(metadata, Util.dk("pk"), staticRow, sortedContent.stream().map(x -> (Unfiltered) x).iterator())) { partition = ImmutableBTreePartition.create(iter); } ColumnMetadata defCol = metadata.getColumn(new ColumnIdentifier("col", true)); ColumnFilter cf = ColumnFilter.selectionBuilder().add(defCol).build(); Function<? super Clusterable, ? extends Clusterable> colFilter = x -> x instanceof Row ? ((Row) x).filter(cf, metadata) : x; Slices slices = Slices.with(metadata.comparator, Slice.make(clustering(KEY_RANGE / 4), clustering(KEY_RANGE * 3 / 4))); Slices multiSlices = makeSlices(); // lastRow assertRowsEqual((Row) get(sortedContent.descendingSet(), x -> x instanceof Row), partition.lastRow()); // get(static) assertRowsEqual(staticRow, partition.getRow(Clustering.STATIC_CLUSTERING)); // get for (int i=0; i < KEY_RANGE; ++i) { Clustering cl = clustering(i); assertRowsEqual(getRow(sortedContent, cl), partition.getRow(cl)); } // isEmpty assertEquals(sortedContent.isEmpty() && staticRow == null, partition.isEmpty()); // hasRows assertEquals(sortedContent.stream().anyMatch(x -> x instanceof Row), partition.hasRows()); // iterator assertIteratorsEqual(sortedContent.stream().filter(x -> x instanceof Row).iterator(), partition.iterator()); // unfiltered iterator assertIteratorsEqual(sortedContent.iterator(), partition.unfilteredIterator()); // unfiltered iterator assertIteratorsEqual(sortedContent.iterator(), partition.unfilteredIterator(ColumnFilter.all(metadata), Slices.ALL, false)); // column-filtered assertIteratorsEqual(sortedContent.stream().map(colFilter).iterator(), partition.unfilteredIterator(cf, Slices.ALL, false)); // sliced assertIteratorsEqual(slice(sortedContent, slices.get(0)), partition.unfilteredIterator(ColumnFilter.all(metadata), slices, false)); assertIteratorsEqual(streamOf(slice(sortedContent, slices.get(0))).map(colFilter).iterator(), partition.unfilteredIterator(cf, slices, false)); // randomly multi-sliced assertIteratorsEqual(slice(sortedContent, multiSlices), partition.unfilteredIterator(ColumnFilter.all(metadata), multiSlices, false)); assertIteratorsEqual(streamOf(slice(sortedContent, multiSlices)).map(colFilter).iterator(), partition.unfilteredIterator(cf, multiSlices, false)); // reversed assertIteratorsEqual(sortedContent.descendingIterator(), partition.unfilteredIterator(ColumnFilter.all(metadata), Slices.ALL, true)); assertIteratorsEqual(sortedContent.descendingSet().stream().map(colFilter).iterator(), partition.unfilteredIterator(cf, Slices.ALL, true)); assertIteratorsEqual(invert(slice(sortedContent, slices.get(0))), partition.unfilteredIterator(ColumnFilter.all(metadata), slices, true)); assertIteratorsEqual(streamOf(invert(slice(sortedContent, slices.get(0)))).map(colFilter).iterator(), partition.unfilteredIterator(cf, slices, true)); assertIteratorsEqual(invert(slice(sortedContent, multiSlices)), partition.unfilteredIterator(ColumnFilter.all(metadata), multiSlices, true)); assertIteratorsEqual(streamOf(invert(slice(sortedContent, multiSlices))).map(colFilter).iterator(), partition.unfilteredIterator(cf, multiSlices, true)); // search iterator testSearchIterator(sortedContent, partition, ColumnFilter.all(metadata), false); testSearchIterator(sortedContent, partition, cf, false); testSearchIterator(sortedContent, partition, ColumnFilter.all(metadata), true); testSearchIterator(sortedContent, partition, cf, true); // sliceable iter testSlicingOfIterators(sortedContent, partition, ColumnFilter.all(metadata), false); testSlicingOfIterators(sortedContent, partition, cf, false); testSlicingOfIterators(sortedContent, partition, ColumnFilter.all(metadata), true); testSlicingOfIterators(sortedContent, partition, cf, true); } void testSearchIterator(NavigableSet<Clusterable> sortedContent, Partition partition, ColumnFilter cf, boolean reversed) { SearchIterator<Clustering, Row> searchIter = partition.searchIterator(cf, reversed); int pos = reversed ? KEY_RANGE : 0; int mul = reversed ? -1 : 1; boolean started = false; while (pos < KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10); pos += skip * mul; Clustering cl = clustering(pos); Row row = searchIter.next(cl); // returns row with deletion, incl. empty row with deletion if (row == null && skip == 0 && started) // allowed to return null if already reported row continue; started = true; Row expected = getRow(sortedContent, cl); assertEquals(expected == null, row == null); if (row == null) continue; assertRowsEqual(expected.filter(cf, metadata), row); } } Slices makeSlices() { int pos = 0; Slices.Builder builder = new Slices.Builder(metadata.comparator); while (pos <= KEY_RANGE) { int skip = rand.nextInt(KEY_RANGE / 10) * (rand.nextInt(3) + 2 / 3); // increased chance of getting 0 pos += skip; int sz = rand.nextInt(KEY_RANGE / 10) + (skip == 0 ? 1 : 0); // if start is exclusive need at least sz 1 Clustering start = clustering(pos); pos += sz; Clustering end = clustering(pos); Slice slice = Slice.make(skip == 0 ? ClusteringBound.exclusiveStartOf(start) : ClusteringBound.inclusiveStartOf(start), ClusteringBound.inclusiveEndOf(end)); builder.add(slice); } return builder.build(); } void testSlicingOfIterators(NavigableSet<Clusterable> sortedContent, AbstractBTreePartition partition, ColumnFilter cf, boolean reversed) { Function<? super Clusterable, ? extends Clusterable> colFilter = x -> x instanceof Row ? ((Row) x).filter(cf, metadata) : x; Slices slices = makeSlices(); // fetch each slice in turn for (Slice slice : (Iterable<Slice>) () -> directed(slices, reversed)) { try (UnfilteredRowIterator slicedIter = partition.unfilteredIterator(cf, Slices.with(metadata.comparator, slice), reversed)) { assertIteratorsEqual(streamOf(directed(slice(sortedContent, slice), reversed)).map(colFilter).iterator(), slicedIter); } } // Fetch all slices at once try (UnfilteredRowIterator slicedIter = partition.unfilteredIterator(cf, slices, reversed)) { List<Iterator<? extends Clusterable>> slicelist = new ArrayList<>(); slices.forEach(slice -> slicelist.add(directed(slice(sortedContent, slice), reversed))); if (reversed) Collections.reverse(slicelist); assertIteratorsEqual(Iterators.concat(slicelist.toArray(new Iterator[0])), slicedIter); } } private<T> Iterator<T> invert(Iterator<T> slice) { Deque<T> dest = new LinkedList<>(); Iterators.addAll(dest, slice); return dest.descendingIterator(); } private Iterator<Clusterable> slice(NavigableSet<Clusterable> sortedContent, Slices slices) { return Iterators.concat(streamOf(slices).map(slice -> slice(sortedContent, slice)).iterator()); } private Iterator<Clusterable> slice(NavigableSet<Clusterable> sortedContent, Slice slice) { // Slice bounds are inclusive bounds, equal only to markers. Matched markers should be returned as one-sided boundaries. RangeTombstoneMarker prev = (RangeTombstoneMarker) sortedContent.headSet(slice.start(), true).descendingSet().stream().filter(x -> x instanceof RangeTombstoneMarker).findFirst().orElse(null); RangeTombstoneMarker next = (RangeTombstoneMarker) sortedContent.tailSet(slice.end(), true).stream().filter(x -> x instanceof RangeTombstoneMarker).findFirst().orElse(null); Iterator<Clusterable> result = sortedContent.subSet(slice.start(), false, slice.end(), false).iterator(); if (prev != null && prev.isOpen(false)) result = Iterators.concat(Iterators.singletonIterator(new RangeTombstoneBoundMarker(slice.start(), prev.openDeletionTime(false))), result); if (next != null && next.isClose(false)) result = Iterators.concat(result, Iterators.singletonIterator(new RangeTombstoneBoundMarker(slice.end(), next.closeDeletionTime(false)))); return result; } private Iterator<Slice> directed(Slices slices, boolean reversed) { return directed(slices.iterator(), reversed); } private <T> Iterator<T> directed(Iterator<T> iter, boolean reversed) { if (!reversed) return iter; return invert(iter); } private <T> Stream<T> streamOf(Iterator<T> iterator) { Iterable<T> iterable = () -> iterator; return streamOf(iterable); } <T> Stream<T> streamOf(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } private void assertIteratorsEqual(Iterator<? extends Clusterable> it1, Iterator<? extends Clusterable> it2) { Clusterable[] a1 = (Clusterable[]) Iterators.toArray(it1, Clusterable.class); Clusterable[] a2 = (Clusterable[]) Iterators.toArray(it2, Clusterable.class); if (Arrays.equals(a1, a2)) return; String a1s = Stream.of(a1).map(x -> "\n" + (x instanceof Unfiltered ? ((Unfiltered) x).toString(metadata) : x.toString())).collect(Collectors.toList()).toString(); String a2s = Stream.of(a2).map(x -> "\n" + (x instanceof Unfiltered ? ((Unfiltered) x).toString(metadata) : x.toString())).collect(Collectors.toList()).toString(); assertArrayEquals("Arrays differ. Expected " + a1s + " was " + a2s, a1, a2); } private Row getRow(NavigableSet<Clusterable> sortedContent, Clustering cl) { NavigableSet<Clusterable> nexts = sortedContent.tailSet(cl, true); if (nexts.isEmpty()) return null; Row row = nexts.first() instanceof Row && metadata.comparator.compare(cl, nexts.first()) == 0 ? (Row) nexts.first() : null; for (Clusterable next : nexts) if (next instanceof RangeTombstoneMarker) { RangeTombstoneMarker rt = (RangeTombstoneMarker) next; if (!rt.isClose(false)) return row; DeletionTime delTime = rt.closeDeletionTime(false); return row == null ? BTreeRow.emptyDeletedRow(cl, Deletion.regular(delTime)) : row.filter(ColumnFilter.all(metadata), delTime, true, metadata); } return row; } private void assertRowsEqual(Row expected, Row actual) { try { assertEquals(expected == null, actual == null); if (expected == null) return; assertEquals(expected.clustering(), actual.clustering()); assertEquals(expected.deletion(), actual.deletion()); assertArrayEquals(Iterables.toArray(expected.cells(), Cell.class), Iterables.toArray(expected.cells(), Cell.class)); } catch (Throwable t) { throw new AssertionError(String.format("Row comparison failed, expected %s got %s", expected, actual), t); } } private static<T> T get(NavigableSet<T> sortedContent, Predicate<T> test) { return sortedContent.stream().filter(test).findFirst().orElse(null); } @Test public void testEmpty() { test(() -> Collections.<Row>emptyList(), null); } @Test public void testStaticOnly() { test(() -> Collections.<Row>emptyList(), makeStaticRow()); } @Test public void testRows() { test(this::generateRows, null); } @Test public void testRowsWithStatic() { test(this::generateRows, makeStaticRow()); } @Test public void testMarkersOnly() { test(this::generateMarkersOnly, null); } @Test public void testMarkersWithStatic() { test(this::generateMarkersOnly, makeStaticRow()); } @Test public void testUnfiltereds() { test(this::generateUnfiltereds, makeStaticRow()); } }
package com.ms_square.debugoverlay; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import java.util.Collections; import java.util.List; public class DebugOverlayService extends Service { private static final String TAG = "DebugOverlayService"; private static final String NOTIFICATION_CHANNEL_ID = "com.ms_square.debugoverlay"; private static final int NOTIFICATION_ID = Integer.MAX_VALUE - 100; private static final String ACTION_SHOW_SUFFIX = ".debugoverlay_ACTION_SHOW"; private static final String ACTION_HIDE_SUFFIX = ".debugoverlay_ACTION_HIDE"; private final IBinder binder = new LocalBinder(); private DebugOverlay.Config config; private List<OverlayModule> overlayModules = Collections.EMPTY_LIST; private OverlayViewManager overlayViewManager; private NotificationManager notificationManager; private boolean modulesStarted; private String actionShow = ""; private String actionHide = ""; public static Intent createIntent(Context context) { return new Intent(context, DebugOverlayService.class); } public class LocalBinder extends Binder { DebugOverlayService getService() { // Return this instance of DebugOverlayService so clients can call public methods return DebugOverlayService.this; } } @Override public void onCreate() { if (DebugOverlay.DEBUG) { Log.i(TAG, "onCreate() called"); } notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); createNotificationChannel(); String packageName = getPackageName(); actionShow = packageName + ACTION_SHOW_SUFFIX; actionHide = packageName + ACTION_HIDE_SUFFIX; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(actionShow); intentFilter.addAction(actionHide); registerReceiver(receiver, intentFilter); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (DebugOverlay.DEBUG) { Log.i(TAG, "onStartCommand() called"); } config = intent.getParcelableExtra(DebugOverlay.KEY_CONFIG); // no need to restart this service return Service.START_NOT_STICKY; } @Override public void onDestroy() { if (DebugOverlay.DEBUG) { Log.i(TAG, "onDestroy() called"); } unregisterReceiver(receiver); cancelNotification(); stopModules(); overlayViewManager.hideDebugSystemOverlay(); } @Nullable @Override public IBinder onBind(Intent intent) { if (DebugOverlay.DEBUG) { Log.i(TAG, "onBind() called"); } return binder; } @Override public void onTaskRemoved(Intent rootIntent) { if (DebugOverlay.DEBUG) { Log.i(TAG, "onTaskRemoved() called"); } stopSelf(); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcastSync(new Intent(DebugOverlay.ACTION_UNBIND)); } public void setOverlayModules(@NonNull List<OverlayModule> overlayModules) { this.overlayModules = overlayModules; } public void setOverlayViewManager(@NonNull OverlayViewManager overlayViewManager) { this.overlayViewManager = overlayViewManager; if (config.isAllowSystemLayer()) { overlayViewManager.showDebugSystemOverlay(); if (config.isShowNotification()) { showNotification(); } } } public void startModules() { if (!modulesStarted) { for (OverlayModule overlayModule : overlayModules) { overlayModule.start(); } modulesStarted = true; if (DebugOverlay.DEBUG) { Log.i(TAG, "Started overlay modules"); } } } public void stopModules() { if (modulesStarted) { for (OverlayModule overlayModule : overlayModules) { overlayModule.stop(); } modulesStarted = false; if (DebugOverlay.DEBUG) { Log.i(TAG, "Stopped overlay modules"); } } } public void updateNotification() { showNotification(); } private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID) == null) { NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, getString(R.string.debugoverlay_notification_channel_name), NotificationManager.IMPORTANCE_LOW); notificationManager.createNotificationChannel(channel); } } } private void showNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.debugoverlay_notification_big_text))) .setSmallIcon(R.drawable.debugoverlay_ic_notification) .setLargeIcon(getAppIcon(this)) .setOngoing(true) .setContentTitle(getString(R.string.debugoverlay_notification_title, getAppName(this), getAppVersion(this))) .setContentText(getString(R.string.debugoverlay_notification_small_text)) .setContentIntent(getNotificationIntent(null)); if (overlayViewManager.isSystemOverlayShown()) { builder.addAction(R.drawable.debugoverlay_ic_action_pause, getString(R.string.debugoverlay_notification_action_hide), getNotificationIntent(actionHide)); } else { builder.addAction(R.drawable.debugoverlay_ic_action_play, getString(R.string.debugoverlay_notification_action_show), getNotificationIntent(actionShow)); } // show the notification startForeground(NOTIFICATION_ID, builder.build()); } private void cancelNotification() { notificationManager.cancel(NOTIFICATION_ID); } private PendingIntent getNotificationIntent(String action) { if (action == null) { PendingIntent pendingIntent = null; if (config.getActivityName() != null) { try { Intent intent = new Intent(this, Class.forName(config.getActivityName())); pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); } catch (ClassNotFoundException ne) { Log.w(TAG, config.getActivityName() + " was not found - " + ne.getMessage()); } } return pendingIntent; } else { Intent intent = new Intent(action); return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); } } private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (actionShow.equals(action)) { overlayViewManager.showDebugSystemOverlay(); startModules(); // update notification showNotification(); } else if (actionHide.equals(action)) { stopModules(); overlayViewManager.hideDebugSystemOverlay(); // update notification showNotification(); } } }; @Nullable private static Bitmap getAppIcon(@NonNull Context context) { Drawable drawable = null; try { drawable = context.getPackageManager().getApplicationIcon(context.getPackageName()); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Package Not found:" + context.getPackageName()); } return (drawable instanceof BitmapDrawable) ? ((BitmapDrawable) drawable).getBitmap() : null; } @NonNull private static String getAppName(@NonNull Context context) { PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo = null; try { applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0); } catch (final PackageManager.NameNotFoundException e) { Log.w(TAG, "Package Not found:" + context.getPackageName()); } return applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo).toString() : "Unknown"; } @NonNull private static String getAppVersion(@NonNull Context context) { String version = "Unknown"; try { version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException ex) { Log.w(TAG, "Package Not found:" + context.getPackageName()); } return version; } }
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.usages.impl; import com.intellij.icons.AllIcons; import com.intellij.ide.tags.TagManager; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vcs.FileStatus; import com.intellij.psi.PsiElement; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.DirtyUI; import com.intellij.ui.RowIcon; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.speedSearch.SpeedSearchUtil; import com.intellij.usageView.UsageTreeColors; import com.intellij.usageView.UsageViewBundle; import com.intellij.usages.TextChunk; import com.intellij.usages.UsageGroup; import com.intellij.usages.UsageTarget; import com.intellij.usages.UsageViewPresentation; import com.intellij.util.FontUtil; import com.intellij.util.SlowOperations; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; final class UsageViewTreeCellRenderer extends ColoredTreeCellRenderer { private static final Logger LOG = Logger.getInstance(UsageViewTreeCellRenderer.class); private static final Insets STANDARD_IPAD_NOWIFI = JBUI.insets(1, 2); private boolean myRowBoundsCalled; private final UsageViewPresentation myPresentation; private final UsageViewImpl myView; private boolean myCalculated; private int myRowHeight = AllIcons.Nodes.AbstractClass.getIconHeight()+2; UsageViewTreeCellRenderer(@NotNull UsageViewImpl view) { myView = view; myPresentation = view.getPresentation(); } private Dimension cachedPreferredSize; @NotNull @Override public Dimension getPreferredSize() { return myCalculated ? super.getPreferredSize() : new Dimension(10, myRowHeight); } @DirtyUI @Override public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (myView.isDisposed()) { return; } SlowOperations.allowSlowOperations(() -> doCustomizeCellRenderer(tree, value, expanded, row)); } private void doCustomizeCellRenderer(@NotNull JTree tree, Object value, boolean expanded, int row) { boolean showAsReadOnly = false; if (value instanceof Node && value != tree.getModel().getRoot()) { Node node = (Node)value; if (!node.isValid()) { append(UsageViewBundle.message("node.invalid") + " ", UsageTreeColors.INVALID_ATTRIBUTES); } if (myPresentation.isShowReadOnlyStatusAsRed() && node.isReadOnly()) { showAsReadOnly = true; } } myCalculated = false; if (value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value; Object userObject = treeNode.getUserObject(); Rectangle visibleRect = ((JViewport)tree.getParent()).getViewRect(); if (!visibleRect.isEmpty()) { //Protection against SOE on some OSes and JDKs IDEA-120631 RowLocation visible = myRowBoundsCalled ? RowLocation.INSIDE_VISIBLE_RECT : isRowVisible(row, visibleRect); myRowBoundsCalled = false; if (visible != RowLocation.INSIDE_VISIBLE_RECT) { // for the node outside visible rect do not compute (expensive) presentation return; } if (!getIpad().equals(STANDARD_IPAD_NOWIFI)) { // for the visible node, return its ipad to the standard value setIpad(STANDARD_IPAD_NOWIFI); } } // we can be called recursively via isRowVisible() if (myCalculated) return; myCalculated = true; if (userObject instanceof UsageTarget) { LOG.assertTrue(treeNode instanceof Node); if (!((Node)treeNode).isValid()) { if (!getCharSequence(false).toString().contains(UsageViewBundle.message("node.invalid"))) { append(UsageViewBundle.message("node.invalid"), UsageTreeColors.INVALID_ATTRIBUTES); } return; } UsageTarget usageTarget = (UsageTarget)userObject; final ItemPresentation presentation = usageTarget.getPresentation(); LOG.assertTrue(presentation != null); if (showAsReadOnly) { append(UsageViewBundle.message("node.readonly") + " ", UsageTreeColors.INVALID_ATTRIBUTES); } final String text = presentation.getPresentableText(); append(text == null ? "" : text, SimpleTextAttributes.REGULAR_ATTRIBUTES); setIcon(presentation.getIcon(expanded)); } else if (treeNode instanceof GroupNode) { GroupNode node = (GroupNode)treeNode; if (node.isRoot()) { append("<root>", patchAttrs(node, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES)); //NON-NLS root is invisible } else { UsageGroup group = node.getGroup(); PsiElement element = group instanceof DataProvider ? CommonDataKeys.PSI_ELEMENT.getData((DataProvider)group) : null; Icon tagIcon = TagManager.appendTags(element, this); append(group.getText(myView), patchAttrs(node, showAsReadOnly ? UsageTreeColors.READ_ONLY_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES)); Icon icon = node.getGroup().getIcon(expanded); if (tagIcon != null) { icon = new RowIcon(tagIcon, icon); } setIcon(icon); } int count = node.getRecursiveUsageCount(); SimpleTextAttributes attributes = patchAttrs(node, UsageTreeColors.NUMBER_OF_USAGES_ATTRIBUTES); append(FontUtil.spaceAndThinSpace() + UsageViewBundle.message("usage.view.counter", count), SimpleTextAttributes.GRAYED_ATTRIBUTES.derive(attributes.getStyle(), null, null, null)); } else if (treeNode instanceof UsageNode) { UsageNode node = (UsageNode)treeNode; setIcon(node.getUsage().getPresentation().getIcon()); if (showAsReadOnly) { append(UsageViewBundle.message("node.readonly") + " ", patchAttrs(node, UsageTreeColors.READ_ONLY_ATTRIBUTES)); } if (node.isValid()) { TextChunk[] text = node.getUsage().getPresentation().getCachedText(); if (text == null) { // either: // 1. the node was never updated yet // 2. the usage presentation have dropped the cached text by itself // (i.e. it was stored by a soft reference and was gc-ed). // In either case, `myView.updateLater()` will eventually re-update the visible nodes. text = new TextChunk[]{new TextChunk(SimpleTextAttributes.GRAY_ATTRIBUTES.toTextAttributes(), UsageViewBundle.message("loading"))}; // Since "loading..." text is not reflected in the node's cached state // we must force the node to recalculate it's bounds on the next view update node.forceUpdate(); myView.updateLater(); } for (int i = 0; i < text.length; i++) { TextChunk textChunk = text[i]; SimpleTextAttributes simples = textChunk.getSimpleAttributesIgnoreBackground(); append(textChunk.getText() + (i == 0 ? " " : ""), patchAttrs(node, simples), true); } } } else if (userObject instanceof String) { append((String)userObject, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); } else { //noinspection HardCodedStringLiteral append(userObject == null ? "" : userObject.toString(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } } else { //noinspection HardCodedStringLiteral append(value.toString(), SimpleTextAttributes.REGULAR_ATTRIBUTES); } SpeedSearchUtil.applySpeedSearchHighlighting(tree, this, true, mySelected); } // computes the node text regardless of the node visibility @NotNull String getPlainTextForNode(Object value) { boolean showAsReadOnly = false; StringBuilder result = new StringBuilder(); if (value instanceof Node) { Node node = (Node)value; if (!node.isValid()) { result.append(UsageViewBundle.message("node.invalid")).append(" "); } if (myPresentation.isShowReadOnlyStatusAsRed() && node.isReadOnly()) { showAsReadOnly = true; } } if (value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value; Object userObject = treeNode.getUserObject(); if (userObject instanceof UsageTarget) { UsageTarget usageTarget = (UsageTarget)userObject; if (usageTarget.isValid()) { final ItemPresentation presentation = usageTarget.getPresentation(); LOG.assertTrue(presentation != null); if (showAsReadOnly) { result.append(UsageViewBundle.message("node.readonly")).append(" "); } final String text = presentation.getPresentableText(); result.append(text == null ? "" : text); } else { result.append(UsageViewBundle.message("node.invalid")); } } else if (treeNode instanceof GroupNode) { GroupNode node = (GroupNode)treeNode; if (node.isRoot()) { result.append("<root>"); } else { result.append(node.getGroup().getText(myView)); } result.append(" (").append(node.getRecursiveUsageCount()).append(")"); } else if (treeNode instanceof UsageNode) { UsageNode node = (UsageNode)treeNode; if (showAsReadOnly) { result.append(UsageViewBundle.message("node.readonly")).append(" "); } if (node.isValid()) { TextChunk[] text = node.getUsage().getPresentation().getText(); for (TextChunk textChunk : text) { result.append(textChunk.getText()); } } } else if (userObject instanceof String) { result.append((String)userObject); } else { result.append(userObject == null ? "" : userObject.toString()); } } else { result.append(value); } return result.toString(); } enum RowLocation { BEFORE_VISIBLE_RECT, INSIDE_VISIBLE_RECT, AFTER_VISIBLE_RECT } @NotNull RowLocation isRowVisible(int row, @NotNull Rectangle visibleRect) { Dimension pref; if (cachedPreferredSize == null) { cachedPreferredSize = pref = getPreferredSize(); } else { pref = cachedPreferredSize; } pref.width = Math.max(visibleRect.width, pref.width); myRowBoundsCalled = true; JTree tree = getTree(); final Rectangle bounds = tree == null ? null : tree.getRowBounds(row); myRowBoundsCalled = false; if (bounds != null) { myRowHeight = bounds.height; } int y = bounds == null ? 0 : bounds.y; TextRange vis = TextRange.from(Math.max(0, visibleRect.y - pref.height), visibleRect.height + pref.height * 2); boolean inside = vis.contains(y); if (inside) { return RowLocation.INSIDE_VISIBLE_RECT; } return y < vis.getStartOffset() ? RowLocation.BEFORE_VISIBLE_RECT : RowLocation.AFTER_VISIBLE_RECT; } private static SimpleTextAttributes patchAttrs(@NotNull Node node, @NotNull SimpleTextAttributes original) { if (node.isExcluded()) { original = new SimpleTextAttributes(original.getStyle() | SimpleTextAttributes.STYLE_STRIKEOUT, original.getFgColor(), original.getWaveColor()); } if (node instanceof GroupNode) { UsageGroup group = ((GroupNode)node).getGroup(); FileStatus fileStatus = group != null ? group.getFileStatus() : null; if (fileStatus != null && fileStatus != FileStatus.NOT_CHANGED) { original = new SimpleTextAttributes(original.getStyle(), fileStatus.getColor(), original.getWaveColor()); } DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent(); if (parent != null && parent.isRoot()) { original = new SimpleTextAttributes(original.getStyle() | SimpleTextAttributes.STYLE_BOLD, original.getFgColor(), original.getWaveColor()); } } return original; } static @NlsContexts.Tooltip String getTooltipFromPresentation(final Object value) { if (value instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value; if (treeNode instanceof UsageNode) { UsageNode node = (UsageNode)treeNode; return node.getUsage().getPresentation().getTooltipText(); } } return null; } }
/* * Copyright (C) 2005 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.base.Objects; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.MutableClassToInstanceMap; import com.google.common.reflect.Invokable; import com.google.common.reflect.Parameter; import com.google.common.reflect.Reflection; import com.google.common.reflect.TypeToken; import junit.framework.Assert; import junit.framework.AssertionFailedError; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; /** * A test utility that verifies that your methods and constructors throw {@link * NullPointerException} or {@link UnsupportedOperationException} whenever null * is passed to a parameter that isn't annotated with {@link Nullable}. * * <p>The tested methods and constructors are invoked -- each time with one * parameter being null and the rest not null -- and the test fails if no * expected exception is thrown. {@code NullPointerTester} uses best effort to * pick non-null default values for many common JDK and Guava types, and also * for interfaces and public classes that have public parameter-less * constructors. When the non-null default value for a particular parameter type * cannot be provided by {@code NullPointerTester}, the caller can provide a * custom non-null default value for the parameter type via {@link #setDefault}. * * @author Kevin Bourrillion * @since 10.0 */ @Beta public final class NullPointerTester { private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create(); private final List<Member> ignoredMembers = Lists.newArrayList(); private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE; /** * Sets a default value that can be used for any parameter of type * {@code type}. Returns this object. */ public <T> NullPointerTester setDefault(Class<T> type, T value) { defaults.putInstance(type, checkNotNull(value)); return this; } /** * Ignore {@code method} in the tests that follow. Returns this object. * * @since 13.0 */ public NullPointerTester ignore(Method method) { ignoredMembers.add(checkNotNull(method)); return this; } /** * Runs {@link #testConstructor} on every constructor in class {@code c} that * has at least {@code minimalVisibility}. */ public void testConstructors(Class<?> c, Visibility minimalVisibility) { for (Constructor<?> constructor : c.getDeclaredConstructors()) { if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) { testConstructor(constructor); } } } /** * Runs {@link #testConstructor} on every public constructor in class {@code * c}. */ public void testAllPublicConstructors(Class<?> c) { testConstructors(c, Visibility.PUBLIC); } /** * Runs {@link #testMethod} on every static method of class {@code c} that has * at least {@code minimalVisibility}, including those "inherited" from * superclasses of the same package. */ public void testStaticMethods(Class<?> c, Visibility minimalVisibility) { for (Method method : minimalVisibility.getStaticMethods(c)) { if (!isIgnored(method)) { testMethod(null, method); } } } /** * Runs {@link #testMethod} on every public static method of class {@code c}, * including those "inherited" from superclasses of the same package. */ public void testAllPublicStaticMethods(Class<?> c) { testStaticMethods(c, Visibility.PUBLIC); } /** * Runs {@link #testMethod} on every instance method of the class of * {@code instance} with at least {@code minimalVisibility}, including those * inherited from superclasses of the same package. */ public void testInstanceMethods(Object instance, Visibility minimalVisibility) { for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) { testMethod(instance, method); } } ImmutableList<Method> getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility) { ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Method method : minimalVisibility.getInstanceMethods(c)) { if (!isIgnored(method)) { builder.add(method); } } return builder.build(); } /** * Runs {@link #testMethod} on every public instance method of the class of * {@code instance}, including those inherited from superclasses of the same * package. */ public void testAllPublicInstanceMethods(Object instance) { testInstanceMethods(instance, Visibility.PUBLIC); } /** * Verifies that {@code method} produces a {@link NullPointerException} * or {@link UnsupportedOperationException} whenever <i>any</i> of its * non-{@link Nullable} parameters are null. * * @param instance the instance to invoke {@code method} on, or null if * {@code method} is static */ public void testMethod(@Nullable Object instance, Method method) { Class<?>[] types = method.getParameterTypes(); for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { testMethodParameter(instance, method, nullIndex); } } /** * Verifies that {@code ctor} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} whenever <i>any</i> of its * non-{@link Nullable} parameters are null. */ public void testConstructor(Constructor<?> ctor) { Class<?> declaringClass = ctor.getDeclaringClass(); checkArgument(Modifier.isStatic(declaringClass.getModifiers()) || declaringClass.getEnclosingClass() == null, "Cannot test constructor of non-static inner class: %s", declaringClass.getName()); Class<?>[] types = ctor.getParameterTypes(); for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { testConstructorParameter(ctor, nullIndex); } } /** * Verifies that {@code method} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. * * @param instance the instance to invoke {@code method} on, or null if * {@code method} is static */ public void testMethodParameter( @Nullable final Object instance, final Method method, int paramIndex) { method.setAccessible(true); testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass()); } /** * Verifies that {@code ctor} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. */ public void testConstructorParameter(Constructor<?> ctor, int paramIndex) { ctor.setAccessible(true); testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass()); } /** Visibility of any method or constructor. */ public enum Visibility { PACKAGE { @Override boolean isVisible(int modifiers) { return !Modifier.isPrivate(modifiers); } }, PROTECTED { @Override boolean isVisible(int modifiers) { return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers); } }, PUBLIC { @Override boolean isVisible(int modifiers) { return Modifier.isPublic(modifiers); } }; abstract boolean isVisible(int modifiers); /** * Returns {@code true} if {@code member} is visible under {@code this} * visibility. */ final boolean isVisible(Member member) { return isVisible(member.getModifiers()); } final Iterable<Method> getStaticMethods(Class<?> cls) { ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Method method : getVisibleMethods(cls)) { if (Invokable.from(method).isStatic()) { builder.add(method); } } return builder.build(); } final Iterable<Method> getInstanceMethods(Class<?> cls) { ConcurrentMap<Signature, Method> map = Maps.newConcurrentMap(); for (Method method : getVisibleMethods(cls)) { if (!Invokable.from(method).isStatic()) { map.putIfAbsent(new Signature(method), method); } } return map.values(); } private ImmutableList<Method> getVisibleMethods(Class<?> cls) { // Don't use cls.getPackage() because it does nasty things like reading // a file. String visiblePackage = Reflection.getPackageName(cls); ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Class<?> type : TypeToken.of(cls).getTypes().classes().rawTypes()) { if (!Reflection.getPackageName(type).equals(visiblePackage)) { break; } for (Method method : type.getDeclaredMethods()) { if (!method.isSynthetic() && isVisible(method)) { builder.add(method); } } } return builder.build(); } } // TODO(benyu): Use labs/reflect/Signature if it graduates. private static final class Signature { private final String name; private final ImmutableList<Class<?>> parameterTypes; Signature(Method method) { this(method.getName(), ImmutableList.copyOf(method.getParameterTypes())); } Signature(String name, ImmutableList<Class<?>> parameterTypes) { this.name = name; this.parameterTypes = parameterTypes; } @Override public boolean equals(Object obj) { if (obj instanceof Signature) { Signature that = (Signature) obj; return name.equals(that.name) && parameterTypes.equals(that.parameterTypes); } return false; } @Override public int hashCode() { return Objects.hashCode(name, parameterTypes); } } /** * Verifies that {@code invokable} produces a {@link NullPointerException} or * {@link UnsupportedOperationException} when the parameter in position {@code * paramIndex} is null. If this parameter is marked {@link Nullable}, this * method does nothing. * * @param instance the instance to invoke {@code invokable} on, or null if * {@code invokable} is static */ private void testParameter(Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) { if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) { return; // there's nothing to test } Object[] params = buildParamList(invokable, paramIndex); try { @SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong. Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable; unsafe.invoke(instance, params); Assert.fail("No exception thrown from " + invokable + Arrays.toString(params) + " for " + testedClass); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (policy.isExpectedType(cause)) { return; } AssertionFailedError error = new AssertionFailedError( "wrong exception thrown from " + invokable + ": " + cause); error.initCause(cause); throw error; } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) { ImmutableList<Parameter> params = invokable.getParameters(); Object[] args = new Object[params.size()]; for (int i = 0; i < args.length; i++) { Parameter param = params.get(i); if (i != indexOfParamToSetToNull) { args[i] = getDefaultValue(param.getType()); if (!isPrimitiveOrNullable(param)) { Assert.assertTrue("No default value found for " + param + " of "+ invokable, args[i] != null); } } } return args; } private <T> T getDefaultValue(TypeToken<T> type) { // We assume that all defaults are generics-safe, even if they aren't, // we take the risk. @SuppressWarnings("unchecked") T defaultValue = (T) defaults.getInstance(type.getRawType()); if (defaultValue != null) { return defaultValue; } @SuppressWarnings("unchecked") // All null values are generics-safe T nullValue = (T) ArbitraryInstances.get(type.getRawType()); if (nullValue != null) { return nullValue; } if (type.getRawType() == Class.class) { // If parameter is Class<? extends Foo>, we return Foo.class @SuppressWarnings("unchecked") T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType(); return defaultClass; } if (type.getRawType() == TypeToken.class) { // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>. @SuppressWarnings("unchecked") T defaultType = (T) getFirstTypeParameter(type.getType()); return defaultType; } if (type.getRawType().isInterface()) { return newDefaultReturningProxy(type); } return null; } private static TypeToken<?> getFirstTypeParameter(Type type) { if (type instanceof ParameterizedType) { return TypeToken.of( ((ParameterizedType) type).getActualTypeArguments()[0]); } else { return TypeToken.of(Object.class); } } private <T> T newDefaultReturningProxy(final TypeToken<T> type) { return new DummyProxy() { @Override <R> R dummyReturnValue(TypeToken<R> returnType) { return getDefaultValue(returnType); } }.newProxy(type); } private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) { if (instance == null) { return Invokable.from(method); } else { return TypeToken.of(instance.getClass()).method(method); } } static boolean isPrimitiveOrNullable(Parameter param) { return param.getType().getRawType().isPrimitive() || param.isAnnotationPresent(Nullable.class); } private boolean isIgnored(Member member) { return member.isSynthetic() || ignoredMembers.contains(member); } /** * Strategy for exception type matching used by {@link NullPointerTester}. */ private enum ExceptionTypePolicy { /** * Exceptions should be {@link NullPointerException} or * {@link UnsupportedOperationException}. */ NPE_OR_UOE() { @Override public boolean isExpectedType(Throwable cause) { return cause instanceof NullPointerException || cause instanceof UnsupportedOperationException; } }, /** * Exceptions should be {@link NullPointerException}, * {@link IllegalArgumentException}, or * {@link UnsupportedOperationException}. */ NPE_IAE_OR_UOE() { @Override public boolean isExpectedType(Throwable cause) { return cause instanceof NullPointerException || cause instanceof IllegalArgumentException || cause instanceof UnsupportedOperationException; } }; public abstract boolean isExpectedType(Throwable cause); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.scripting.jsp.jasper; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagInfo; import org.apache.sling.scripting.jsp.jasper.compiler.Compiler; import org.apache.sling.scripting.jsp.jasper.compiler.JDTCompiler; import org.apache.sling.scripting.jsp.jasper.compiler.JspRuntimeContext; import org.apache.sling.scripting.jsp.jasper.compiler.JspUtil; import org.apache.sling.scripting.jsp.jasper.compiler.Localizer; import org.apache.sling.scripting.jsp.jasper.compiler.ServletWriter; /** * A place holder for various things that are used through out the JSP * engine. This is a per-request/per-context data structure. Some of * the instance variables are set at different points. * * Most of the path-related stuff is here - mangling names, versions, dirs, * loading resources and dealing with uris. * * @author Anil K. Vijendran * @author Harish Prabandham * @author Pierre Delisle * @author Costin Manolache * @author Kin-man Chung */ public class JspCompilationContext { private Map<String, URL> tagFileJarUrls; private String className; private String jspUri; private boolean isErrPage; private String basePackageName; private String derivedPackageName; private String servletJavaFileName; private String javaPath; private String classFileName; private String contentType; private ServletWriter writer; private Options options; private Compiler jspCompiler; private String baseURI; private String outputDir; private ServletContext context; private JspRuntimeContext rctxt; private boolean isTagFile; private boolean protoTypeMode; private TagInfo tagInfo; private URL tagFileJarUrl; private final boolean defaultIsSession; // jspURI _must_ be relative to the context public JspCompilationContext(String jspUri, boolean isErrPage, Options options, ServletContext context, JspRuntimeContext rctxt, boolean defaultIsSession) { this.jspUri = canonicalURI(jspUri); this.isErrPage = isErrPage; this.options = options; this.context = context; this.baseURI = jspUri.substring(0, jspUri.lastIndexOf('/') + 1); // hack fix for resolveRelativeURI if (baseURI == null) { baseURI = "/"; } else if (baseURI.charAt(0) != '/') { // strip the basde slash since it will be combined with the // uriBase to generate a file baseURI = "/" + baseURI; } if (baseURI.charAt(baseURI.length() - 1) != '/') { baseURI += '/'; } this.rctxt = rctxt; this.tagFileJarUrls = new HashMap<String, URL>(); this.basePackageName = Constants.JSP_PACKAGE_NAME; this.defaultIsSession = defaultIsSession; } public JspCompilationContext(String tagfile, TagInfo tagInfo, Options options, ServletContext context, JspRuntimeContext rctxt, boolean defaultIsSession, URL tagFileJarUrl) { this(tagfile, false, options, context, rctxt, defaultIsSession); this.isTagFile = true; this.tagInfo = tagInfo; this.tagFileJarUrl = tagFileJarUrl; } /** * What class loader to use for loading classes while compiling * this JSP? */ public ClassLoader getClassLoader() { return getRuntimeContext().getIOProvider().getClassLoader(); } /** ---------- Input/Output ---------- */ /** * Creates an output stream to the given file * @param fileName The path to the file to write to * @return The OutputStream to the file * @throws IOException If an error occurrs creating the output stream. */ public OutputStream getOutputStream(String fileName) throws IOException { return getRuntimeContext().getIOProvider().getOutputStream(fileName); } /** * Creates an input stream from the given file * @param fileName The path to the file to read from * @return The InputStream from the file * @throws FileNotFoundException If the file cannot be found * @throws IOException If an error occurrs creating the intput stream. */ public InputStream getInputStream(String fileName) throws FileNotFoundException, IOException { return getRuntimeContext().getIOProvider().getInputStream(fileName); } /** * Removes a (generated) file. * @param fileName The path to the file to remove. * @return <code>true</code> if the file has been removed. */ public boolean delete(String fileName) { return getRuntimeContext().getIOProvider().delete(fileName); } /** * Renams then old file to the new file * @return <code>true</code> if the file has been renamed * */ public boolean rename(String oldFileName, String newFileName) { return getRuntimeContext().getIOProvider().rename(oldFileName, newFileName); } /** * The output directory to generate code into. The output directory * is make up of the scratch directory, which is provide in Options, * plus the directory derived from the package name. */ public String getOutputDir() { if (outputDir == null) { createOutputDir(); } return outputDir; } /** * Create a "Compiler" object based on some init param data. This * is not done yet. Right now we're just hardcoding the actual * compilers that are created. */ private Compiler createCompiler() { if (jspCompiler != null ) { return jspCompiler; } jspCompiler = new JDTCompiler(defaultIsSession); jspCompiler.init(this); return jspCompiler; } public Compiler getCompiler() { return jspCompiler; } /** ---------- Access resources in the webapp ---------- */ /** * Get the full value of a URI relative to this compilations context * uses current file as the base. */ public String resolveRelativeUri(String uri) { // sometimes we get uri's massaged from File(String), so check for // a root directory deperator char if (uri.startsWith("/") || uri.startsWith(File.separator)) { return uri; } return baseURI + uri; } /** * Gets a resource as a stream, relative to the meanings of this * context's implementation. * @return a null if the resource cannot be found or represented * as an InputStream. */ public java.io.InputStream getResourceAsStream(String res) { return context.getResourceAsStream(canonicalURI(res)); } public URL getResource(String res) throws MalformedURLException { return context.getResource(canonicalURI(res)); } @SuppressWarnings("unchecked") public Set<String> getResourcePaths(String path) { return context.getResourcePaths(canonicalURI(path)); } /** * Gets the actual path of a URI relative to the context of * the compilation. */ public String getRealPath(String path) { if (context != null) { return context.getRealPath(path); } return path; } /** * Returns the tag-file-name-to-JAR-file map of this compilation unit, * which maps tag file names to the JAR files in which the tag files are * packaged. * * The map is populated when parsing the tag-file elements of the TLDs * of any imported taglibs. */ public URL getTagFileJarUrl(String tagFile) { return this.tagFileJarUrls.get(tagFile); } public void setTagFileJarUrl(String tagFile, URL tagFileURL) { this.tagFileJarUrls.put(tagFile, tagFileURL); } /** * Returns the JAR file in which the tag file for which this * JspCompilationContext was created is packaged, or null if this * JspCompilationContext does not correspond to a tag file, or if the * corresponding tag file is not packaged in a JAR. */ public URL getTagFileJarUrl() { return this.tagFileJarUrl; } /* ==================== Common implementation ==================== */ /** * Just the class name (does not include package name) of the * generated class. */ public String getServletClassName() { if (className != null) { return className; } if (isTagFile) { className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); if (lastIndex != -1) { className = className.substring(lastIndex + 1); } } else { int iSep = jspUri.lastIndexOf('/') + 1; className = JspUtil.makeJavaIdentifier(jspUri.substring(iSep)); } return className; } /** * Path of the JSP URI. Note that this is not a file name. This is * the context rooted URI of the JSP file. */ public String getJspFile() { return jspUri; } /** * Are we processing something that has been declared as an * errorpage? */ public boolean isErrorPage() { return isErrPage; } public void setErrorPage(boolean isErrPage) { this.isErrPage = isErrPage; } public boolean isTagFile() { return isTagFile; } public TagInfo getTagInfo() { return tagInfo; } public void setTagInfo(TagInfo tagi) { tagInfo = tagi; } /** * True if we are compiling a tag file in prototype mode. * ie we only generate codes with class for the tag handler with empty * method bodies. */ public boolean isPrototypeMode() { return protoTypeMode; } public void setPrototypeMode(boolean pm) { protoTypeMode = pm; } /** * Package name for the generated class is make up of the base package * name, which is user settable, and the derived package name. The * derived package name directly mirrors the file heirachy of the JSP page. */ public String getServletPackageName() { if (isTagFile()) { String className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); String pkgName = ""; if (lastIndex != -1) { pkgName = className.substring(0, lastIndex); } return pkgName; } else if (basePackageName == null || basePackageName.length() == 0) { return getDerivedPackageName(); } else { String dPackageName = getDerivedPackageName(); if (dPackageName.length() == 0) { return basePackageName; } return basePackageName + '.' + getDerivedPackageName(); } } protected String getDerivedPackageName() { if (derivedPackageName == null) { int iSep = jspUri.lastIndexOf('/'); derivedPackageName = (iSep > 0) ? JspUtil.makeJavaPackage(jspUri.substring(1,iSep)) : ""; } return derivedPackageName; } /** * Full path name of the Java file into which the servlet is being * generated. */ public String getServletJavaFileName() { if (servletJavaFileName == null) { servletJavaFileName = getOutputDir() + getServletClassName() + ".java"; } return servletJavaFileName; } /** * Get hold of the Options object for this context. */ public Options getOptions() { return options; } public ServletContext getServletContext() { return context; } public JspRuntimeContext getRuntimeContext() { return rctxt; } /** * Path of the Java file relative to the work directory. */ public String getJavaPath() { if (javaPath != null) { return javaPath; } if (isTagFile()) { String tagName = tagInfo.getTagClassName(); javaPath = tagName.replace('.', '/') + ".java"; } else { javaPath = getServletPackageName().replace('.', '/') + '/' + getServletClassName() + ".java"; } return javaPath; } public String getClassFileName() { if (classFileName == null) { classFileName = getOutputDir() + getServletClassName() + ".class"; } return classFileName; } /** * Get the content type of this JSP. * * Content type includes content type and encoding. */ public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } /** * Where is the servlet being generated? */ public ServletWriter getWriter() { return writer; } public void setWriter(ServletWriter writer) { this.writer = writer; } /** * Gets the 'location' of the TLD associated with the given taglib 'uri'. * * @return An array of two Strings: The first element denotes the real * path to the TLD. If the path to the TLD points to a jar file, then the * second element denotes the name of the TLD entry in the jar file. * Returns null if the given uri is not associated with any tag library * 'exposed' in the web application. */ public String[] getTldLocation(String uri) throws JasperException { String[] location = getOptions().getTldLocationsCache().getLocation(uri); return location; } /** * Are we keeping generated code around? */ public boolean keepGenerated() { return getOptions().getKeepGenerated(); } // ==================== Compile and reload ==================== public JasperException compile() { final Compiler c = createCompiler(); try { c.removeGeneratedFiles(); c.compile(); } catch (final JasperException ex) { return ex; } catch (final IOException ioe) { final JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ioe); return je; } catch (final Exception ex) { JasperException je = new JasperException( Localizer.getMessage("jsp.error.unable.compile"), ex); return je; } finally { c.clean(); } return null; } // ==================== Manipulating the class ==================== public Class<?> load() throws JasperException { try { String name; if (isTagFile()) { name = tagInfo.getTagClassName(); } else { name = getServletPackageName() + "." + getServletClassName(); } final Class<?> servletClass = getClassLoader().loadClass(name); return servletClass; } catch (ClassNotFoundException cex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.load"), cex); } catch (Exception ex) { throw new JasperException(Localizer.getMessage("jsp.error.unable.compile"), ex); } } // ==================== protected methods ==================== public void checkOutputDir() { getOutputDir(); } private boolean makeOutputDir() { return getRuntimeContext().getIOProvider().mkdirs(outputDir); } private void createOutputDir() { String path = null; if (isTagFile()) { String tagName = tagInfo.getTagClassName(); path = tagName.replace('.', '/'); path = path.substring(0, path.lastIndexOf('/')); } else { path = getServletPackageName().replace('.', '/'); } // Append servlet or tag handler path to scratch dir outputDir = options.getScratchDir() + File.separator + path + File.separator; if (!makeOutputDir()) { throw new IllegalStateException(Localizer.getMessage("jsp.error.outputfolder")); } } private static final boolean isPathSeparator(char c) { return (c == '/' || c == '\\'); } private static final String canonicalURI(String s) { if (s == null) return null; StringBuffer result = new StringBuffer(); final int len = s.length(); int pos = 0; while (pos < len) { char c = s.charAt(pos); if ( isPathSeparator(c) ) { /* * multiple path separators. * 'foo///bar' -> 'foo/bar' */ while (pos+1 < len && isPathSeparator(s.charAt(pos+1))) { ++pos; } if (pos+1 < len && s.charAt(pos+1) == '.') { /* * a single dot at the end of the path - we are done. */ if (pos+2 >= len) break; switch (s.charAt(pos+2)) { /* * self directory in path * foo/./bar -> foo/bar */ case '/': case '\\': pos += 2; continue; /* * two dots in a path: go back one hierarchy. * foo/bar/../baz -> foo/baz */ case '.': // only if we have exactly _two_ dots. if (pos+3 < len && isPathSeparator(s.charAt(pos+3))) { pos += 3; int separatorPos = result.length()-1; while (separatorPos >= 0 && ! isPathSeparator(result .charAt(separatorPos))) { --separatorPos; } if (separatorPos >= 0) result.setLength(separatorPos); continue; } } } } result.append(c); ++pos; } return result.toString(); } }
/* * * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * / */ package io.druid.server.lookup; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.metamx.common.ISE; import com.metamx.common.logger.Logger; import io.druid.concurrent.Execs; import io.druid.query.lookup.LookupExtractor; import io.druid.server.lookup.cache.polling.OnHeapPollingCache; import io.druid.server.lookup.cache.polling.PollingCache; import io.druid.server.lookup.cache.polling.PollingCacheFactory; import javax.validation.constraints.NotNull; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; public class PollingLookup extends LookupExtractor { private static final Logger LOGGER = new Logger(PollingLookup.class); private final long pollPeriodMs; private final DataFetcher dataFetcher; private final PollingCacheFactory cacheFactory; private final AtomicReference<CacheRefKeeper> refOfCacheKeeper = new AtomicReference<>(); private final ListeningScheduledExecutorService scheduledExecutorService; private final AtomicBoolean isOpen = new AtomicBoolean(false); private final ListenableFuture<?> pollFuture; private final String id = Integer.toHexString(System.identityHashCode(this)); public PollingLookup( long pollPeriodMs, DataFetcher dataFetcher, PollingCacheFactory cacheFactory ) { this.pollPeriodMs = pollPeriodMs; this.dataFetcher = Preconditions.checkNotNull(dataFetcher); this.cacheFactory = cacheFactory == null ? new OnHeapPollingCache.OnHeapPollingCacheProvider() : cacheFactory; refOfCacheKeeper.set(new CacheRefKeeper(this.cacheFactory.makeOf(dataFetcher.fetchAll()))); if (pollPeriodMs > 0) { scheduledExecutorService = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor( Execs.makeThreadFactory("PollingLookup-" + id, Thread.MIN_PRIORITY) )); pollFuture = scheduledExecutorService.scheduleWithFixedDelay( pollAndSwap(), pollPeriodMs, pollPeriodMs, TimeUnit.MILLISECONDS ); } else { scheduledExecutorService = null; pollFuture = null; } this.isOpen.set(true); } public void close() { LOGGER.info("Closing polling lookup [%s]", id); synchronized (isOpen) { isOpen.getAndSet(false); if (pollFuture != null) { pollFuture.cancel(true); scheduledExecutorService.shutdown(); } CacheRefKeeper cacheRefKeeper = refOfCacheKeeper.getAndSet(null); if (cacheRefKeeper != null) { cacheRefKeeper.doneWithIt(); } } } @Override public String apply(@NotNull String key) { final CacheRefKeeper cacheRefKeeper = refOfCacheKeeper.get(); if (cacheRefKeeper == null) { throw new ISE("Cache reference is null WTF"); } final PollingCache cache = cacheRefKeeper.getAndIncrementRef(); try { if (cache == null) { // it must've been closed after swapping while I was getting it. Try again. return this.apply(key); } return Strings.emptyToNull((String) cache.get(key)); } finally { if (cacheRefKeeper != null && cache != null) { cacheRefKeeper.doneWithIt(); } } } @Override public List<String> unapply(final String value) { CacheRefKeeper cacheRefKeeper = refOfCacheKeeper.get(); if (cacheRefKeeper == null) { throw new ISE("pollingLookup id [%s] is closed", id); } PollingCache cache = cacheRefKeeper.getAndIncrementRef(); try { if (cache == null) { // it must've been closed after swapping while I was getting it. Try again. return this.unapply(value); } return cache.getKeys(value); } finally { if (cacheRefKeeper != null && cache != null) { cacheRefKeeper.doneWithIt(); } } } @Override public byte[] getCacheKey() { return LookupExtractionModule.getRandomCacheKey(); } private Runnable pollAndSwap() { return new Runnable() { @Override public void run() { LOGGER.debug("Polling and swapping of PollingLookup [%s]", id); CacheRefKeeper newCacheKeeper = new CacheRefKeeper(cacheFactory.makeOf(dataFetcher.fetchAll())); CacheRefKeeper oldCacheKeeper = refOfCacheKeeper.getAndSet(newCacheKeeper); if (oldCacheKeeper != null) { oldCacheKeeper.doneWithIt(); } } }; } @Override public int hashCode() { int result = (int) (pollPeriodMs ^ (pollPeriodMs >>> 32)); result = 31 * result + dataFetcher.hashCode(); result = 31 * result + cacheFactory.hashCode(); return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PollingLookup)) { return false; } PollingLookup that = (PollingLookup) o; if (pollPeriodMs != that.pollPeriodMs) { return false; } if (!dataFetcher.equals(that.dataFetcher)) { return false; } return cacheFactory.equals(that.cacheFactory); } public boolean isOpen() { return isOpen.get(); } protected static class CacheRefKeeper { private final PollingCache pollingCache; private final AtomicLong refCounts = new AtomicLong(0L); CacheRefKeeper(PollingCache pollingCache) {this.pollingCache = pollingCache;} PollingCache getAndIncrementRef() { synchronized (refCounts) { if (refCounts.get() < 0) { return null; } refCounts.incrementAndGet(); return pollingCache; } } void doneWithIt() { synchronized (refCounts) { if (refCounts.get() == 0) { pollingCache.close(); } refCounts.decrementAndGet(); } } } }
package org.jivesoftware.openfire.plugin.gojara.messagefilter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import org.dom4j.Element; import org.dom4j.Node; import org.jivesoftware.openfire.PacketRouter; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.interceptor.PacketInterceptor; import org.jivesoftware.openfire.interceptor.PacketRejectedException; import org.jivesoftware.openfire.plugin.gojara.messagefilter.processors.*; import org.jivesoftware.openfire.plugin.gojara.sessions.GojaraAdminManager; import org.jivesoftware.openfire.plugin.gojara.sessions.TransportSessionManager; import org.jivesoftware.openfire.plugin.gojara.utils.XpathHelper; import org.jivesoftware.openfire.roster.RosterManager; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.util.ConcurrentHashSet; import org.jivesoftware.util.JiveGlobals; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet; import org.xmpp.packet.Presence; /** * This is the only Interceptor GoJara uses. Each IQ/Message/Presence is checked if it is of interest to us, so we can * process it accordingly. This is done in the specific Processors. The Interceptor keeps a set of currently connected * Transports. * * @author axel.frederik.brand * @author Holger Bergunde * */ public class MainInterceptor implements PacketInterceptor { private static final Logger Log = LoggerFactory.getLogger(MainInterceptor.class); private Set<String> activeTransports = new ConcurrentHashSet<String>(); /** * For referencing the abstract remote Processors */ private Map<String, AbstractRemoteRosterProcessor> packetProcessors = new HashMap<String, AbstractRemoteRosterProcessor>(); private TransportSessionManager tSessionManager = TransportSessionManager.getInstance(); private GojaraAdminManager gojaraAdminmanager = GojaraAdminManager.getInstance(); private XMPPServer server; private Boolean frozen; public MainInterceptor() { Log.info("Created MainInterceptor for GoJara Plugin."); server = XMPPServer.getInstance(); RosterManager rosterManager = server.getRosterManager(); AbstractRemoteRosterProcessor iqRegisteredProcessor = new DiscoIQRegisteredProcessor(); AbstractRemoteRosterProcessor iqRosterPayloadProcessor = new IQRosterPayloadProcessor(rosterManager); AbstractRemoteRosterProcessor nonPersistantProcessor = new NonPersistantRosterProcessor(rosterManager); AbstractRemoteRosterProcessor statisticsProcessor = new StatisticsProcessor(); AbstractRemoteRosterProcessor updateToComponentProcessor = new ClientToComponentUpdateProcessor(activeTransports); AbstractRemoteRosterProcessor whitelistProcessor = new WhitelistProcessor(activeTransports); AbstractRemoteRosterProcessor mucfilterProcessor = new MucFilterProcessor(); AbstractRemoteRosterProcessor gojaraAdminProcessor = new GojaraAdminProcessor(); packetProcessors.put("sparkIQRegistered", iqRegisteredProcessor); packetProcessors.put("iqRosterPayload", iqRosterPayloadProcessor); packetProcessors.put("handleNonPersistant", nonPersistantProcessor); packetProcessors.put("statisticsProcessor", statisticsProcessor); packetProcessors.put("clientToComponentUpdate", updateToComponentProcessor); packetProcessors.put("whitelistProcessor", whitelistProcessor); packetProcessors.put("mucfilterProcessor", mucfilterProcessor); packetProcessors.put("gojaraAdminProcessor", gojaraAdminProcessor); frozen = false; } public boolean addTransport(String subDomain) { Log.info("Adding " + subDomain + " to watched Transports."); boolean retval = this.activeTransports.add(subDomain); if (retval) { tSessionManager.addTransport(subDomain); gojaraAdminmanager.testAdminConfiguration(subDomain); } return retval; } public boolean removeTransport(String subDomain) { Log.info("Removing " + subDomain + " from watched Transports."); tSessionManager.removeTransport(subDomain); gojaraAdminmanager.gatewayUnregistered(subDomain); return this.activeTransports.remove(subDomain); } public void freeze() { Log.info("Freezing GoJara Maininterceptor."); frozen = true; } /** * As our Set of Subdomains is a Hash of Strings like icq.domain.tld, if we want to check if a jid CONTAINS a * watched subdomain we need to iterate over the set. We also return the subdomain as a string so we can use it if * we find it. */ private String searchJIDforSubdomain(String jid) { if (jid.length() > 0) { for (String subdomain : activeTransports) { if (jid.contains(subdomain)) return subdomain; } } return ""; } /** * This Interceptor tests if GoJara needs to process this package. We decided to do one global Interceptor so we * would'nt redundantly test for cases we already checked in previous Interceptors, also we have only one big ugly * If Structure to maintain instead of several. * * @see org.jivesoftware.openfire.interceptor.PacketInterceptor#interceptPacket (org.xmpp.packet.Packet, * org.jivesoftware.openfire.session.Session, boolean, boolean) */ public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { if (frozen) return; String from = ""; String to = ""; if (!processed || (incoming && processed)) { try { if (packet.getFrom() != null) from = packet.getFrom().toString(); if (packet.getTo() != null) to = packet.getTo().toString(); } catch (IllegalArgumentException e) { Log.debug("There was an illegal JID while intercepting Message for GoJara. Not Intercepting it! " + e.getMessage()); return; } } if (incoming && !processed) { if (packet instanceof IQ) { IQ iqPacket = (IQ) packet; Element query = iqPacket.getChildElement(); if (query == null) return; // Jabber:IQ:roster Indicates Client to Component update or Rosterpush else if (query.getNamespaceURI().equals("jabber:iq:roster")) { if (!activeTransports.contains(from) && to.length() == 0 && iqPacket.getType().equals(IQ.Type.set)) packetProcessors.get("clientToComponentUpdate").process(packet, "", to, from); else if (from.length() > 0 && activeTransports.contains(from)) packetProcessors.get("iqRosterPayload").process(packet, from, to, from); } // SPARK IQ REGISTERED Feature else if (query.getNamespaceURI().equals("http://jabber.org/protocol/disco#info") && to.length() > 0 && activeTransports.contains(to) && iqPacket.getType().equals(IQ.Type.get)) { packetProcessors.get("sparkIQRegistered").process(packet, to, to, from); } // JABBER:IQ:LAST - Autoresponse Feature else if (JiveGlobals.getBooleanProperty("plugin.remoteroster.iqLastFilter", false) && query.getNamespaceURI().equals("jabber:iq:last")) { String to_s = searchJIDforSubdomain(to); if (to_s.length() > 0 && iqPacket.getType().equals(IQ.Type.get)) throw new PacketRejectedException(); } } // Gojara Admin Manager Feature - Intercept responses to ADHOC commands sent via AdminManager else if (packet instanceof Message && activeTransports.contains(from) && to.contains("gojaraadmin")) { packetProcessors.get("gojaraAdminProcessor").process(packet, from, to, from); } // NONPERSISTANT Feature else { if (!JiveGlobals.getBooleanProperty("plugin.remoteroster.persistent", false)) { if (packet instanceof Presence && activeTransports.contains(from)) packetProcessors.get("handleNonPersistant").process(packet, from, to, from); } } } else if (incoming && processed) { // We ignore Pings from S2 to S2 itself. // STATISTICS - Feature String from_searched = searchJIDforSubdomain(from); String to_searched = searchJIDforSubdomain(to); String subdomain = from_searched.length() == 0 ? to_searched : from_searched; if (!from.equals(to) && subdomain.length() > 0) packetProcessors.get("statisticsProcessor").process(packet, subdomain, to, from); // TransportSession Feature if (packet instanceof Presence && activeTransports.contains(from)) { Presence presence_packet = (Presence) packet; if (presence_packet.getType() == null) { tSessionManager.connectUserTo(from, packet.getTo().getNode().toString()); } else if (presence_packet.getType() != null && presence_packet.getType().equals(Presence.Type.unavailable)) { tSessionManager.disconnectUserFrom(from, packet.getTo().getNode().toString()); } } // TransportSession Feature - track Registrations and unregistrations so we can reset unsuccesfull ones else if (packet instanceof IQ && activeTransports.contains(to)) { IQ iqPacket = (IQ) packet; Element query = iqPacket.getChildElement(); if (query == null) return; /* * Okay, so now we have a IQ Packet with a query xmlns: jabber:iq:register Spark sends registrations and * unregistrations in such a query, register has a x xmls jabber:iq:gateway:register, unregister is just * a <remove/> element Gajim sends the whole form with x xmlns jabber:x:data type="submit", where a * field var=unregister value of 0 is a registration, and unregister = 1 is unregistration */ if (query.getNamespaceURI().equals("jabber:iq:register") && iqPacket.getType().equals(IQ.Type.set)) { // spark + gajim unregister if (query.element("remove") != null) tSessionManager.removeRegistrationOfUserFromDB(to, iqPacket.getFrom().getNode().toString()); else if (query.element("x") != null) { Element xElem = query.element("x"); String xNamespace = xElem.getNamespaceURI(); // spark register if (xNamespace.equals("jabber:iq:gateway:register")) tSessionManager.registerUserTo(to, iqPacket.getFrom().getNode().toString()); // Gajim register + presence push else if (xNamespace.equals("jabber:x:data") && xElem.attribute("type").getText().equals("submit")) { tSessionManager.registerUserTo(to, iqPacket.getFrom().getNode().toString()); presencePush(packet.getTo(), packet.getFrom(), 150); } } } } } else if (!incoming && !processed) { if (packet instanceof IQ) { IQ iqPacket = (IQ) packet; Element query = iqPacket.getChildElement(); if (query == null) return; // DISCO#ITEMS - Whitelisting Feature if (query.getNamespaceURI().equals("http://jabber.org/protocol/disco#items")) packetProcessors.get("whitelistProcessor").process(packet, "", to, from); // DISCO#INFO - MUC-Filter-Feature else if (JiveGlobals.getBooleanProperty("plugin.remoteroster.mucFilter", false) && query.getNamespaceURI().equals("http://jabber.org/protocol/disco#info") && from.length() > 0 && activeTransports.contains(from)) packetProcessors.get("mucfilterProcessor").process(packet, from, to, from); // GAJIM presence push when connecting... probably doesnt really belong here but by now we would have // 50processors for every edge case we handle... // If roster is persistent and we dont block presences no need to do this since presences are being // pushed by OF anyways else if (JiveGlobals.getBooleanProperty("plugin.remoteroster.gajimBroadcast", false)) { if (to.contains("Gajim") && query.getNamespaceURI().equals("jabber:iq:roster") && iqPacket.getType().equals(IQ.Type.result)) { List<Node> nodes = XpathHelper.findNodesInDocument(iqPacket.getElement().getDocument(), "//roster:item"); for (Node n : nodes) { String jid = n.valueOf("@jid"); if (activeTransports.contains(jid)) { JID pushTo = new JID(jid); presencePush(pushTo, iqPacket.getTo(), 3000); } } } } } else if (JiveGlobals.getBooleanProperty("plugin.remoteroster.blockPresences", true) && packet instanceof Presence) { /* * We block Presences to users of a subdomain (except transport itself) so OF/S2 wont log you in * automatically if you have a subdomain user in your roster. This prevents some clients from logging * automatically, as the clients dont send a specific presence to the transport. We could do a presence * push if we see them come online, but that would do the same as just not intercepting these presences, * as the problem is really the client */ String to_s = searchJIDforSubdomain(to); if (to_s.length() > 0 && !activeTransports.contains(to)) throw new PacketRejectedException(); } } } /** * Just pushes a available presence, we need this for GAJIM Client as it does not push available presence after * registering We also wait a little so after register transport is on users roster. Really didnt wanted this here * but doesnt really belong anywhere else * * @param to * @param from * @param delay MS until the job should be done */ private void presencePush(final JID to, final JID from, int delay) { TimerTask pushPresenceTask = new TimerTask() { @Override public void run() { PacketRouter router = server.getPacketRouter(); Packet presence = new Presence(); presence.setTo(to); presence.setFrom(from); router.route(presence); } }; Timer timer = new Timer(); timer.schedule(pushPresenceTask, delay); } }
package org.ow2.contrail.common.implementation.ovf.ovf_StAXParsing; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URI; import java.util.HashMap; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.XMLEvent; import org.apache.log4j.Logger; import org.ow2.contrail.common.exceptions.MalformedOVFException; import org.ow2.contrail.common.implementation.application.ApplicationDescriptor; import org.ow2.contrail.common.implementation.ovf.Disk; import org.ow2.contrail.common.implementation.ovf.File; import org.ow2.contrail.common.implementation.ovf.SharedDisk; import org.ow2.contrail.common.implementation.ovf.OVFProperty; import org.ow2.contrail.common.implementation.ovf.OVFVirtualNetwork; /** * Creates an application descriptor from an OVF file using StAX to parse the OVF file. * * @author Giacomo Maestrelli (giacomo.maestrelli@gmail.com) under supervision of Massimo Coppola */ public class OVFStAXParser { public static String ovfNames="{http://schemas.dmtf.org/ovf/envelope/1}"; public static final String ovfNames2="{http://schemas.dmtf.org/ovf/envelope/2}"; public static final String ovf1="http://schemas.dmtf.org/ovf/envelope/1"; public static final String ovf2="http://schemas.dmtf.org/ovf/envelope/2"; private static Logger logger = Logger.getLogger(OVFStAXParser.class); /** * Parses an OVF file * * @param file file to be parsed * @return an ApplicationDescriptor representing the OVF file parsed * @throws FileNotFoundException * @throws XMLStreamException * @throws MalformedOVFException */ public ApplicationDescriptor parseOVF(URI file) throws FileNotFoundException,XMLStreamException, MalformedOVFException{ return parseOVF(new FileInputStream(file.getPath()),false); } public ApplicationDescriptor parseOVF(String file) throws FileNotFoundException,XMLStreamException, MalformedOVFException{ InputStream i = this.getClass().getResourceAsStream("/" + file); return parseOVF(i, false); } /** * Parses an <em>InputStream</em> representing an OVF * * @param str an input stream generating XML events * @param isValidating if <em>true</em> turns on validation for input stream * @return an ApplicationDescriptor representing an OVF stream or null if input cannot be parsed as a valid OVF * @throws XMLStreamException * @throws MalformedOVFException */ public ApplicationDescriptor parseOVF(InputStream str, boolean isValidating) throws XMLStreamException, MalformedOVFException{ ApplicationDescriptor appDesc = null; XMLEventReader r = null; try { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_VALIDATING, isValidating); XMLEventReader event_reader = factory.createXMLEventReader(str); r = factory.createFilteredReader(event_reader, new FilterOVFElement()); } catch (Exception e){ throw new XMLStreamException(e.getMessage()); } while (r.hasNext()){ XMLEvent e = r.nextEvent(); /*EVENT DISPATCHER*/ switch (e.getEventType()) { case XMLEvent.START_ELEMENT: // if(e.asStartElement().getName().getLocalPart().contentEquals("Envelope") && e.getSchemaType()!=null && e.getSchemaType().getNamespaceURI().contentEquals(ovfNames)) if (e.asStartElement().getName().getLocalPart().contentEquals("Envelope")){ String namespace = e.asStartElement().getName().getNamespaceURI(); if (!namespace.equals(ovf1)){ ovfNames = ovfNames2; logger.info("The namespace is " + ovfNames); } appDesc = new ApplicationDescriptor(e,r,this); } else throw new MalformedOVFException(); break; } } return appDesc; } /** * parses References Section of an OVF file(seen as a stream of XMLEvent) and maps <em>id</em> attribute (as string ) of ovf <em>File</em> tag * to ovf <em>File</em> tag <em>href</em> attribute (as string) * * @param files HashMap for mapping * @param e current event * @param r XMLEventReader instance setted on OVF file to parse * @throws XMLStreamException */ public void parseReferencesTag(HashMap<String,File> files,XMLEvent e,XMLEventReader r) throws XMLStreamException{ boolean end = false; while (!end&&r.hasNext()){ e=r.nextEvent(); end=e.isEndElement()&&e.asEndElement().getName().getLocalPart().contentEquals("References"); if (!end) switch (e.getEventType()){ case XMLEvent.START_ELEMENT: if (e.asStartElement().getName().getLocalPart().contentEquals("File")){ Attribute attrId=e.asStartElement(). getAttributeByName(QName.valueOf(ovfNames+"id")); Attribute attrHref=e.asStartElement(). getAttributeByName(QName.valueOf(ovfNames+"href")); Attribute attrSize=e.asStartElement(). getAttributeByName(QName.valueOf(ovfNames+"size")); long size; try { size = Long.parseLong(attrSize.getValue().trim()); files.put(attrId.getValue(),new File(attrId.getValue(),attrHref.getValue(),size)); } catch (java.lang.NullPointerException eNull){ } } break; } } } /** * parses DiskSection of an OVF file(seen as a stream of XMLEvent) and sets relation between Files and Disks * * @param disks * @param files * @param e * @param r * @throws XMLStreamException */ public void parseDiskSectionTag(HashMap<String,Disk> disks, HashMap<String,File> files, XMLEvent e, XMLEventReader r) throws XMLStreamException{ boolean end=false; while(!end&&r.hasNext()){ e=r.nextEvent(); end=(e.isEndElement()&&e.asEndElement().getName().getLocalPart().contentEquals("DiskSection")); if(!end) switch(e.getEventType()){ case XMLEvent.START_ELEMENT: if(e.asStartElement().getName().getLocalPart().contentEquals("Disk")){ String id= e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"diskId")). getValue().trim(); //FIXME disk in ovf file can be empty String fileRef = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"fileRef")) .getValue().trim(); disks.put("ovf:/disk/" + id, new Disk(files.get(fileRef),id) ); Attribute attParRef = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"parentRef")); if (attParRef!=null){ Disk parent=disks.get("ovf:/disk/" +attParRef.getValue()); Disk child=disks.get("ovf:/disk/" +id); child.setParent(parent); parent.addChild(child); } } break; } } } public void parseSharedDiskSectionTag(HashMap<String, SharedDisk> sdisks, HashMap<String,File> files, XMLEvent e, XMLEventReader r) throws XMLStreamException{ boolean end = false; while (!end && r.hasNext()){ e = r.nextEvent(); end = (e.isEndElement() && e.asEndElement().getName().getLocalPart().contentEquals("SharedDiskSection")); if (!end) switch (e.getEventType()){ case XMLEvent.START_ELEMENT: if (e.asStartElement().getName().getLocalPart().contentEquals("SharedDisk")){ String id = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames + "diskId")). getValue().trim(); //FIXME disk in ovf file can be empty String capacity = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames + "capacity")) .getValue().trim(); String format = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames + "format")) .getValue().trim(); String fileRef = null; try { fileRef = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames + "fileRef")) .getValue().trim(); } catch (NullPointerException ex){ fileRef = ""; } sdisks.put("ovf:/disk/" + id, new SharedDisk(id, files.get(fileRef), capacity, format) ); Attribute attParRef = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames + "parentRef")); if (attParRef!=null){ SharedDisk parent = sdisks.get("ovf:/disk/" + attParRef.getValue()); SharedDisk child = sdisks.get("ovf:/disk/" + id); child.setParent(parent); parent.addChild(child); } } break; } } } /** * parses NetworkSection of an OVF file(seen as a stream of XMLEvent) * * @param network * @param e * @param r * @throws XMLStreamException */ public void parseNetworkSectionTag(HashMap<String, OVFVirtualNetwork> network, XMLEvent e, XMLEventReader r) throws XMLStreamException{ boolean end=false; while(!end && r.hasNext()){ e = r.nextEvent(); end=(e.isEndElement() && e.asEndElement().getName().getLocalPart().contentEquals("NetworkSection")); if(!end){ switch(e.getEventType()){ case XMLEvent.START_ELEMENT: if(e.asStartElement().getName().getLocalPart().contentEquals("Network")) { String name = e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"name")).getValue().trim(); network.put(name,new OVFVirtualNetwork(name,e,r)); } break; } } } } /** * parses Property section of an OVF file(seen as a stream of XMLEvent) * * @param prop * @param e * @param r * @throws XMLStreamException */ public void parseProductSection(OVFProperty prop,XMLEvent e,XMLEventReader r) throws XMLStreamException{ boolean end = false; while (!end && r.hasNext()){ e = r.nextEvent(); end = (e.isEndElement()&&e.asEndElement().getName().getLocalPart().contentEquals("Property")); if (!end){ switch(e.getEventType()){ case XMLEvent.START_ELEMENT: if(e.asStartElement().getName().getLocalPart().contentEquals("Label")){ String msg=e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"msgid"))!=null? e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"msgid")).getValue():null; prop.setLabel(msg,r.getElementText()); } else if(e.asStartElement().getName().getLocalPart().contentEquals("Description")){ String msg=e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"msgid"))!=null? e.asStartElement().getAttributeByName(QName.valueOf(ovfNames+"msgid")).getValue():null; prop.setDescription(msg,r.getElementText()); } break; } } } } }
/* * Copyright 2010-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.auth; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.ClientConfiguration; import com.amazonaws.SdkClientException; import com.amazonaws.retry.PredefinedBackoffStrategies; import com.amazonaws.retry.RetryPolicy; import com.amazonaws.retry.RetryUtils; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityRequest; import com.amazonaws.services.securitytoken.model.AssumeRoleWithWebIdentityResult; import com.amazonaws.services.securitytoken.model.IDPCommunicationErrorException; import com.amazonaws.services.securitytoken.model.InvalidIdentityTokenException; import java.io.BufferedReader; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.Callable; public class STSAssumeRoleWithWebIdentitySessionCredentialsProvider implements AWSSessionCredentialsProvider, Closeable { /** * The client for starting STS sessions. */ private final AWSSecurityTokenService securityTokenService; /** * The arn of the role to be assumed. */ private final String roleArn; /** * An identifier for the assumed role session. */ private final String roleSessionName; /** * Absolute path to the JWT file containing the web identity token. */ private final String webIdentityTokenFile; private final Callable<SessionCredentialsHolder> refreshCallable = new Callable<SessionCredentialsHolder>() { @Override public SessionCredentialsHolder call() throws Exception { return newSession(); } }; /** * Handles the refreshing of sessions. Ideally this should be final but #setSTSClientEndpoint * forces us to create a new one. */ private volatile RefreshableTask<SessionCredentialsHolder> refreshableTask; private RefreshableTask<SessionCredentialsHolder> createRefreshableTask() { return new RefreshableTask.Builder<SessionCredentialsHolder>() .withRefreshCallable(refreshCallable) .withBlockingRefreshPredicate(new ShouldDoBlockingSessionRefresh()) .withAsyncRefreshPredicate(new ShouldDoAsyncSessionRefresh()).build(); } /** * The following private constructor reads state from the builder and sets the appropriate * parameters accordingly * <p> * When public constructors are called, this constructors is deferred to with a null value for * roleExternalId and endpoint The inner Builder class can be used to construct an object that * actually has a value for roleExternalId and endpoint * * @throws IllegalArgumentException if both an AWSCredentials and AWSCredentialsProvider have * been set on the builder */ private STSAssumeRoleWithWebIdentitySessionCredentialsProvider(Builder builder) { this.roleArn = builder.roleArn; this.roleSessionName = builder.roleSessionName; this.webIdentityTokenFile = builder.webIdentityTokenFile; this.securityTokenService = buildStsClient(builder); this.refreshableTask = createRefreshableTask(); } /** * Construct a new STS client from the settings in the builder. * * @param builder Configured builder * @return New instance of AWSSecurityTokenService * @throws IllegalArgumentException if builder configuration is inconsistent */ private static AWSSecurityTokenService buildStsClient(Builder builder) throws IllegalArgumentException { if (builder.sts != null) { return builder.sts; } RetryPolicy retryPolicy = new RetryPolicy( new StsRetryCondition(), new PredefinedBackoffStrategies.SDKDefaultBackoffStrategy(), 3, true); ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.setRetryPolicy(retryPolicy); return AWSSecurityTokenServiceClientBuilder.standard() .withClientConfiguration(clientConfiguration) .withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials())) .build(); } @Override public AWSSessionCredentials getCredentials() { return refreshableTask.getValue().getSessionCredentials(); } @Override public void refresh() { refreshableTask.forceGetValue(); } /** * Starts a new session by sending a request to the AWS Security Token Service (STS) to assume a * Role using the long lived AWS credentials. This class then vends the short lived session * credentials for the assumed Role sent back from STS. */ private SessionCredentialsHolder newSession() { AssumeRoleWithWebIdentityRequest assumeRoleRequest = new AssumeRoleWithWebIdentityRequest() .withRoleArn(roleArn) .withWebIdentityToken(getWebIdentityToken()) .withRoleSessionName(roleSessionName); AssumeRoleWithWebIdentityResult assumeRoleResult = securityTokenService.assumeRoleWithWebIdentity(assumeRoleRequest); return new SessionCredentialsHolder(assumeRoleResult.getCredentials()); } private String getWebIdentityToken() { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(webIdentityTokenFile), "UTF-8")); return br.readLine(); } catch (FileNotFoundException e) { throw new SdkClientException("Unable to locate specified web identity token file: " + webIdentityTokenFile); } catch (IOException e) { throw new SdkClientException("Unable to read web identity token from file: " + webIdentityTokenFile); } finally { try { br.close(); } catch (Exception ignored) { } } } /** * Shut down this credentials provider, shutting down the thread that performs asynchronous credential refreshing. This * should not be invoked if the credentials provider is still in use by an AWS client. */ @Override public void close() { refreshableTask.close(); } /** * Provides a builder pattern to avoid combinatorial explosion of the number of parameters that * are passed to constructors. The builder introspects which parameters have been set and calls * the appropriate constructor. */ public static final class Builder { private final String roleArn; private final String roleSessionName; private final String webIdentityTokenFile; private AWSSecurityTokenService sts; /** * @param roleArn Required roleArn parameter used when starting a session * @param roleSessionName Required roleSessionName parameter used when starting a session */ public Builder(String roleArn, String roleSessionName, String webIdentityTokenFile) { if (roleArn == null || roleSessionName == null || webIdentityTokenFile == null) { throw new NullPointerException( "You must specify a value for roleArn, roleSessionName and webIdentityTokenFile"); } this.roleArn = roleArn; this.roleSessionName = roleSessionName; this.webIdentityTokenFile = webIdentityTokenFile; } /** * Sets a preconfigured STS client to use for the credentials provider. See {@link * com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder} for an easy * way to configure and create an STS client. * * @param sts Custom STS client to use. * @return This object for chained calls. */ public Builder withStsClient(AWSSecurityTokenService sts) { this.sts = sts; return this; } /** * Build the configured provider * * @return the configured STSAssumeRoleSessionCredentialsProvider */ public STSAssumeRoleWithWebIdentitySessionCredentialsProvider build() { return new STSAssumeRoleWithWebIdentitySessionCredentialsProvider(this); } } static class StsRetryCondition implements com.amazonaws.retry.RetryPolicy.RetryCondition { @Override public boolean shouldRetry(AmazonWebServiceRequest originalRequest, AmazonClientException exception, int retriesAttempted) { // Always retry on client exceptions caused by IOException if (exception.getCause() instanceof IOException) return true; if (exception instanceof InvalidIdentityTokenException || exception.getCause() instanceof InvalidIdentityTokenException) return true; if (exception instanceof IDPCommunicationErrorException || exception.getCause() instanceof IDPCommunicationErrorException) return true; // Only retry on a subset of service exceptions if (exception instanceof AmazonServiceException) { AmazonServiceException ase = (AmazonServiceException)exception; /* * For 500 internal server errors and 503 service * unavailable errors, we want to retry, but we need to use * an exponential back-off strategy so that we don't overload * a server with a flood of retries. */ if (RetryUtils.isRetryableServiceException(ase)) return true; /* * Throttling is reported as a 400 error from newer services. To try * and smooth out an occasional throttling error, we'll pause and * retry, hoping that the pause is long enough for the request to * get through the next time. */ if (RetryUtils.isThrottlingException(ase)) return true; /* * Clock skew exception. If it is then we will get the time offset * between the device time and the server time to set the clock skew * and then retry the request. */ if (RetryUtils.isClockSkewError(ase)) return true; } return false; } } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1; import com.google.api.core.BetaApi; import com.google.api.gax.httpjson.ApiMessage; import java.util.LinkedList; import java.util.List; import java.util.Objects; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("by GAPIC") @BetaApi /** Contains a list of firewalls. */ public final class FirewallList implements ApiMessage { private final String id; private final List<Firewall> items; private final String kind; private final String nextPageToken; private final String selfLink; private final Warning warning; private FirewallList() { this.id = null; this.items = null; this.kind = null; this.nextPageToken = null; this.selfLink = null; this.warning = null; } private FirewallList( String id, List<Firewall> items, String kind, String nextPageToken, String selfLink, Warning warning) { this.id = id; this.items = items; this.kind = kind; this.nextPageToken = nextPageToken; this.selfLink = selfLink; this.warning = warning; } @Override public Object getFieldValue(String fieldName) { if ("id".equals(fieldName)) { return id; } if ("items".equals(fieldName)) { return items; } if ("kind".equals(fieldName)) { return kind; } if ("nextPageToken".equals(fieldName)) { return nextPageToken; } if ("selfLink".equals(fieldName)) { return selfLink; } if ("warning".equals(fieldName)) { return warning; } return null; } @Nullable @Override public ApiMessage getApiMessageRequestBody() { return null; } @Nullable @Override /** * The fields that should be serialized (even if they have empty values). If the containing * message object has a non-null fieldmask, then all the fields in the field mask (and only those * fields in the field mask) will be serialized. If the containing object does not have a * fieldmask, then only non-empty fields will be serialized. */ public List<String> getFieldMask() { return null; } /** [Output Only] Unique identifier for the resource; defined by the server. */ public String getId() { return id; } /** A list of Firewall resources. */ public List<Firewall> getItemsList() { return items; } /** [Output Only] Type of resource. Always compute#firewallList for lists of firewalls. */ public String getKind() { return kind; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. */ public String getNextPageToken() { return nextPageToken; } /** [Output Only] Server-defined URL for this resource. */ public String getSelfLink() { return selfLink; } /** [Output Only] Informational warning message. */ public Warning getWarning() { return warning; } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(FirewallList prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } public static FirewallList getDefaultInstance() { return DEFAULT_INSTANCE; } private static final FirewallList DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new FirewallList(); } public static class Builder { private String id; private List<Firewall> items; private String kind; private String nextPageToken; private String selfLink; private Warning warning; Builder() {} public Builder mergeFrom(FirewallList other) { if (other == FirewallList.getDefaultInstance()) return this; if (other.getId() != null) { this.id = other.id; } if (other.getItemsList() != null) { this.items = other.items; } if (other.getKind() != null) { this.kind = other.kind; } if (other.getNextPageToken() != null) { this.nextPageToken = other.nextPageToken; } if (other.getSelfLink() != null) { this.selfLink = other.selfLink; } if (other.getWarning() != null) { this.warning = other.warning; } return this; } Builder(FirewallList source) { this.id = source.id; this.items = source.items; this.kind = source.kind; this.nextPageToken = source.nextPageToken; this.selfLink = source.selfLink; this.warning = source.warning; } /** [Output Only] Unique identifier for the resource; defined by the server. */ public String getId() { return id; } /** [Output Only] Unique identifier for the resource; defined by the server. */ public Builder setId(String id) { this.id = id; return this; } /** A list of Firewall resources. */ public List<Firewall> getItemsList() { return items; } /** A list of Firewall resources. */ public Builder addAllItems(List<Firewall> items) { if (this.items == null) { this.items = new LinkedList<>(); } this.items.addAll(items); return this; } /** A list of Firewall resources. */ public Builder addItems(Firewall items) { if (this.items == null) { this.items = new LinkedList<>(); } this.items.add(items); return this; } /** [Output Only] Type of resource. Always compute#firewallList for lists of firewalls. */ public String getKind() { return kind; } /** [Output Only] Type of resource. Always compute#firewallList for lists of firewalls. */ public Builder setKind(String kind) { this.kind = kind; return this; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. */ public String getNextPageToken() { return nextPageToken; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. */ public Builder setNextPageToken(String nextPageToken) { this.nextPageToken = nextPageToken; return this; } /** [Output Only] Server-defined URL for this resource. */ public String getSelfLink() { return selfLink; } /** [Output Only] Server-defined URL for this resource. */ public Builder setSelfLink(String selfLink) { this.selfLink = selfLink; return this; } /** [Output Only] Informational warning message. */ public Warning getWarning() { return warning; } /** [Output Only] Informational warning message. */ public Builder setWarning(Warning warning) { this.warning = warning; return this; } public FirewallList build() { return new FirewallList(id, items, kind, nextPageToken, selfLink, warning); } public Builder clone() { Builder newBuilder = new Builder(); newBuilder.setId(this.id); newBuilder.addAllItems(this.items); newBuilder.setKind(this.kind); newBuilder.setNextPageToken(this.nextPageToken); newBuilder.setSelfLink(this.selfLink); newBuilder.setWarning(this.warning); return newBuilder; } } @Override public String toString() { return "FirewallList{" + "id=" + id + ", " + "items=" + items + ", " + "kind=" + kind + ", " + "nextPageToken=" + nextPageToken + ", " + "selfLink=" + selfLink + ", " + "warning=" + warning + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof FirewallList) { FirewallList that = (FirewallList) o; return Objects.equals(this.id, that.getId()) && Objects.equals(this.items, that.getItemsList()) && Objects.equals(this.kind, that.getKind()) && Objects.equals(this.nextPageToken, that.getNextPageToken()) && Objects.equals(this.selfLink, that.getSelfLink()) && Objects.equals(this.warning, that.getWarning()); } return false; } @Override public int hashCode() { return Objects.hash(id, items, kind, nextPageToken, selfLink, warning); } }
package com.krishagni.catissueplus.core.administrative.domain.factory.impl; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.StringUtils; import com.krishagni.catissueplus.core.administrative.domain.DistributionOrder; import com.krishagni.catissueplus.core.administrative.domain.DistributionOrderItem; import com.krishagni.catissueplus.core.administrative.domain.DistributionProtocol; import com.krishagni.catissueplus.core.administrative.domain.Site; import com.krishagni.catissueplus.core.administrative.domain.User; import com.krishagni.catissueplus.core.administrative.domain.factory.DistributionOrderErrorCode; import com.krishagni.catissueplus.core.administrative.domain.factory.DistributionOrderFactory; import com.krishagni.catissueplus.core.administrative.domain.factory.DistributionProtocolErrorCode; import com.krishagni.catissueplus.core.administrative.domain.factory.SiteErrorCode; import com.krishagni.catissueplus.core.administrative.domain.factory.UserErrorCode; import com.krishagni.catissueplus.core.administrative.events.DistributionOrderDetail; import com.krishagni.catissueplus.core.administrative.events.DistributionOrderItemDetail; import com.krishagni.catissueplus.core.administrative.events.DistributionProtocolDetail; import com.krishagni.catissueplus.core.biospecimen.domain.Specimen; import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode; import com.krishagni.catissueplus.core.biospecimen.events.SpecimenInfo; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.common.errors.ActivityStatusErrorCode; import com.krishagni.catissueplus.core.common.errors.ErrorType; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; import com.krishagni.catissueplus.core.common.events.UserSummary; import com.krishagni.catissueplus.core.common.util.AuthUtil; import com.krishagni.catissueplus.core.common.util.Status; public class DistributionOrderFactoryImpl implements DistributionOrderFactory { private DaoFactory daoFactory; public void setDaoFactory(DaoFactory daoFactory) { this.daoFactory = daoFactory; } @Override public DistributionOrder createDistributionOrder(DistributionOrderDetail detail, DistributionOrder.Status status) { DistributionOrder order = new DistributionOrder(); OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR); order.setId(detail.getId()); setName(detail, order, ose); setDistributionProtocol(detail, order, ose); setRequester(detail, order, ose); setReceivingSite(detail, order, ose); setDistributionDate(detail, order, ose); setDistributor(detail, order, ose); setOrderItems(detail, order, ose); setStatus(detail, status, order, ose); setActivityStatus(detail, order, ose); setTrackingUrl(detail, order, ose); setComments(detail, order, ose); ose.checkAndThrow(); return order; } private void setName(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { String name = detail.getName(); if (StringUtils.isBlank(name)) { ose.addError(DistributionOrderErrorCode.NAME_REQUIRED); return; } order.setName(name); } private void setDistributionProtocol(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { DistributionProtocolDetail dpDetail = detail.getDistributionProtocol(); Long dpId = dpDetail != null ? dpDetail.getId() : null; String dpShortTitle = dpDetail != null ? dpDetail.getShortTitle() : null; if (dpId == null && StringUtils.isBlank(dpShortTitle)) { ose.addError(DistributionOrderErrorCode.DP_REQUIRED); return; } DistributionProtocol dp = null; if (dpId != null) { dp = daoFactory.getDistributionProtocolDao().getById(dpId); } else { dp = daoFactory.getDistributionProtocolDao().getByShortTitle(dpShortTitle); } if (dp == null) { ose.addError(DistributionProtocolErrorCode.NOT_FOUND); return; } order.setDistributionProtocol(dp); } private void setRequester(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { User requester = getUser(detail.getRequester(), null); if (requester == null) { ose.addError(UserErrorCode.NOT_FOUND); return; } if (!requester.getInstitute().equals(order.getInstitute())) { ose.addError(DistributionOrderErrorCode.REQUESTER_DOES_NOT_BELONG_DP_INST); return; } order.setRequester(requester); } private void setReceivingSite(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { Long siteId = detail.getSiteId(); String siteName = detail.getSiteName(); if (siteId == null && StringUtils.isBlank(siteName)) { ose.addError(SiteErrorCode.NOT_FOUND); return; } Site site = null; if (siteId != null) { site = daoFactory.getSiteDao().getById(siteId); } else { site = daoFactory.getSiteDao().getSiteByName(siteName); } if (site == null) { ose.addError(SiteErrorCode.NOT_FOUND); return; } if (!site.getInstitute().equals(order.getInstitute())) { ose.addError(DistributionOrderErrorCode.RECV_SITE_DOES_NOT_BELONG_DP_INST); return; } order.setSite(site); } private void setDistributionDate(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { Date creationDate = detail.getCreationDate(); if (creationDate == null) { creationDate = Calendar.getInstance().getTime(); } else if (creationDate.after(Calendar.getInstance().getTime())) { ose.addError(DistributionOrderErrorCode.INVALID_CREATION_DATE); return; } order.setCreationDate(creationDate); Date executionDate = detail.getExecutionDate(); if (executionDate == null) { executionDate = Calendar.getInstance().getTime(); } else if (executionDate.after(Calendar.getInstance().getTime())) { ose.addError(DistributionOrderErrorCode.INVALID_EXECUTION_DATE); return; } order.setExecutionDate(executionDate); } private void setDistributor(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { User distributor = getUser(detail.getDistributor(), AuthUtil.getCurrentUser()); if (distributor == null) { ose.addError(UserErrorCode.NOT_FOUND); return; } order.setDistributor(distributor); } private void setOrderItems(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { Set<DistributionOrderItem> items = new HashSet<DistributionOrderItem>(); Set<Long> specimens = new HashSet<Long>(); for (DistributionOrderItemDetail oid : detail.getOrderItems()) { DistributionOrderItem item = getOrderItem(oid, order, ose); if (item != null) { items.add(item); specimens.add(item.getSpecimen().getId()); } } if (specimens.size() < detail.getOrderItems().size()) { ose.addError(DistributionOrderErrorCode.DUPLICATE_SPECIMENS); return; } order.setOrderItems(items); } private void setStatus(DistributionOrderDetail detail, DistributionOrder.Status initialStatus, DistributionOrder order, OpenSpecimenException ose) { if (initialStatus != null) { order.setStatus(initialStatus); return; } if (detail.getStatus() == null) { ose.addError(DistributionOrderErrorCode.INVALID_STATUS); } DistributionOrder.Status status = null; try { status = DistributionOrder.Status.valueOf(detail.getStatus()); } catch (IllegalArgumentException iae) { ose.addError(DistributionOrderErrorCode.INVALID_STATUS); return; } order.setStatus(status); } private void setActivityStatus(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { String activityStatus = detail.getActivityStatus(); if (StringUtils.isBlank(activityStatus)) { activityStatus = Status.ACTIVITY_STATUS_ACTIVE.getStatus(); } if (!Status.isValidActivityStatus(activityStatus)) { ose.addError(ActivityStatusErrorCode.INVALID); return; } order.setActivityStatus(activityStatus); } private void setTrackingUrl(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { order.setTrackingUrl(detail.getTrackingUrl()); } private void setComments(DistributionOrderDetail detail, DistributionOrder order, OpenSpecimenException ose) { order.setComments(detail.getComments()); } private User getUser(UserSummary userSummary, User defaultUser) { if (userSummary == null) { return defaultUser; } User user = defaultUser; if (userSummary.getId() != null) { user = daoFactory.getUserDao().getById(userSummary.getId()); } else if (StringUtils.isNotBlank(userSummary.getLoginName()) && StringUtils.isNotBlank(userSummary.getDomain())) { user = daoFactory.getUserDao().getUser(userSummary.getLoginName(), userSummary.getDomain()); } return user; } private DistributionOrderItem getOrderItem(DistributionOrderItemDetail detail, DistributionOrder order, OpenSpecimenException ose) { Specimen specimen = getSpecimen(detail.getSpecimen(), ose); if (specimen == null) { return null; } if (detail.getQuantity() == null || detail.getQuantity() <= 0) { ose.addError(DistributionOrderErrorCode.INVALID_QUANTITY); return null; } DistributionOrderItem orderItem = new DistributionOrderItem(); orderItem.setQuantity(detail.getQuantity()); orderItem.setSpecimen(specimen); orderItem.setOrder(order); try { orderItem.setStatus(DistributionOrderItem.Status.valueOf(detail.getStatus())); } catch (IllegalArgumentException iae) { ose.addError(DistributionOrderErrorCode.INVALID_SPECIMEN_STATUS); } return orderItem; } private Specimen getSpecimen(SpecimenInfo info, OpenSpecimenException ose) { Specimen specimen = null; Object key = null; if (info.getId() != null) { key = info.getId(); specimen = daoFactory.getSpecimenDao().getById(info.getId()); } else if (StringUtils.isNotBlank(info.getLabel())) { key = info.getLabel(); specimen = daoFactory.getSpecimenDao().getByLabel(info.getLabel()); } if (specimen == null) { ose.addError(SpecimenErrorCode.NOT_FOUND, key); } return specimen; } }
/** * Copyright 2014 Matthew Congrove * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mcongrove.pebble; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollFunction; import org.appcelerator.kroll.KrollModule; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.common.TiConfig; import org.appcelerator.titanium.TiApplication; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.UUID; import org.json.JSONArray; import org.json.JSONObject; import com.getpebble.android.kit.PebbleKit; import com.getpebble.android.kit.util.PebbleDictionary; @Kroll.module(name="TitaniumPebble", id="com.mcongrove.pebble") public class TitaniumPebbleModule extends KrollModule { private static final String LCAT = "Pebble"; private static UUID uuid; private int connectedCount = 0; private boolean isListeningToPebble = false; private static HashMap<Integer,HashMap<String,KrollFunction>> callbacks = new HashMap<Integer,HashMap<String,KrollFunction>>(); private static Integer transactionCounter = 0; private BroadcastReceiver connectedReceiver = null; private BroadcastReceiver disconnectedReceiver = null; private PebbleKit.PebbleDataReceiver dataReceiver = null; private PebbleKit.PebbleAckReceiver ackReceiver = null; private PebbleKit.PebbleNackReceiver nackReceiver = null; public TitaniumPebbleModule() { super(); } public TiApplication getApplicationContext() { return TiApplication.getInstance(); } // Lifecycle Events @Kroll.onAppCreate public static void onAppCreate(TiApplication app) { } @Override public void onPause(Activity activity) { super.onPause(activity); if(connectedReceiver != null) { getApplicationContext().unregisterReceiver(connectedReceiver); connectedReceiver = null; } if(disconnectedReceiver != null) { getApplicationContext().unregisterReceiver(disconnectedReceiver); disconnectedReceiver = null; } if(dataReceiver != null) { getApplicationContext().unregisterReceiver(dataReceiver); dataReceiver = null; } if(ackReceiver != null) { getApplicationContext().unregisterReceiver(ackReceiver); ackReceiver = null; } if(nackReceiver != null) { getApplicationContext().unregisterReceiver(nackReceiver); nackReceiver = null; } } @Override public void onResume(Activity activity) { super.onResume(activity); if(isListeningToPebble) { addReceivers(); } } @Override public void onDestroy(Activity activity) { super.onDestroy(activity); } // Methods @Kroll.method private void listenToConnectedWatch() { Log.d(LCAT, "listenToConnectedWatch: Listening"); if(!checkWatchConnected()) { Log.w(LCAT, "listenToConnectedWatch: No watch connected"); return; } if(!isListeningToPebble) { isListeningToPebble = true; } addReceivers(); } @Kroll.method private void addReceivers() { if(isListeningToPebble) { if(connectedReceiver == null) { connectedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(LCAT, "watchDidConnect"); setConnectedCount(0); fireEvent("watchConnected", new Object[] {}); } }; PebbleKit.registerPebbleConnectedReceiver(getApplicationContext(), connectedReceiver); } if(disconnectedReceiver == null) { disconnectedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(LCAT, "watchDidDisconnect"); setConnectedCount(0); fireEvent("watchDisconnected", new Object[] {}); } }; PebbleKit.registerPebbleDisconnectedReceiver(getApplicationContext(), disconnectedReceiver); } if(dataReceiver == null) { dataReceiver = new PebbleKit.PebbleDataReceiver(uuid) { @Override public void receiveData(final Context context, final int transactionId, final PebbleDictionary data) { if(!data.contains(0)) { Log.e(LCAT, "listenToConnectedWatch: Received message, data corrupt"); PebbleKit.sendNackToPebble(context, transactionId); return; } PebbleKit.sendAckToPebble(context, transactionId); try { JSONArray jsonArray = new JSONArray(data.toJsonString()); if(jsonArray.length() > 0) { JSONObject jsonObject = jsonArray.getJSONObject(0); if(jsonObject.has("value")) { Log.i(LCAT, "listenToConnectedWatch: Received message"); HashMap message = new HashMap(); message.put("message", jsonObject.getString("value")); fireEvent("update", message); } } } catch(Throwable e) { Log.e(LCAT, "listenToConnectedWatch: Received message, data corrupt"); } } }; PebbleKit.registerReceivedDataHandler(getApplicationContext(), dataReceiver); } if(ackReceiver == null) { ackReceiver = new PebbleKit.PebbleAckReceiver(uuid) { @Override public void receiveAck(Context context, int transactionId) { Log.i(LCAT, "Received ACK for transaction: " + transactionId); if(callbacks.containsKey(transactionId)) { HashMap callbackArray = (HashMap)callbacks.get(transactionId); if(callbackArray.containsKey("success")) { KrollFunction successCallback = (KrollFunction)callbackArray.get("success"); successCallback.call(getKrollObject(), new Object[] {}); } } } }; PebbleKit.registerReceivedAckHandler(getApplicationContext(), ackReceiver); } if(nackReceiver == null) { nackReceiver = new PebbleKit.PebbleNackReceiver(uuid) { @Override public void receiveNack(Context context, int transactionId) { Log.e(LCAT, "Received NACK for transaction: " + transactionId); if(callbacks.containsKey(transactionId)) { HashMap callbackArray = (HashMap)callbacks.get(transactionId); if(callbackArray.containsKey("error")) { KrollFunction errorCallback = (KrollFunction)callbackArray.get("error"); errorCallback.call(getKrollObject(), new Object[] {}); } } } }; PebbleKit.registerReceivedNackHandler(getApplicationContext(), nackReceiver); } } } @Kroll.method public void setAppUUID(String uuidString) { uuid = UUID.fromString(uuidString); } @Kroll.method public boolean checkWatchConnected() { try { boolean connected = PebbleKit.isWatchConnected(getApplicationContext()); if(!connected) { Log.w(LCAT, "checkWatchConnected: No watch connected"); } return connected; } catch(SecurityException e) { return false; } } @Kroll.getProperty @Kroll.method public int getConnectedCount() { return connectedCount; } @Kroll.setProperty @Kroll.method public void setConnectedCount(int ignore) { if(checkWatchConnected()) { connectedCount = 1; } else { connectedCount = 0; } } @Kroll.method public void connect(HashMap args) { Log.d(LCAT, "connect"); final KrollFunction successCallback = (KrollFunction)args.get("success"); final KrollFunction errorCallback = (KrollFunction)args.get("error"); if(!PebbleKit.areAppMessagesSupported(getApplicationContext())) { Log.e(LCAT, "connect: Watch does not support messages"); if(errorCallback != null) { errorCallback.call(getKrollObject(), new Object[] {}); } return; } setConnectedCount(0); listenToConnectedWatch(); Log.d(LCAT, "connect: Messages supported"); if(successCallback != null) { successCallback.call(getKrollObject(), new Object[] {}); } } @Kroll.method public void getVersionInfo(HashMap args) { Log.d(LCAT, "getVersionInfo"); final KrollFunction successCallback = (KrollFunction)args.get("success"); final KrollFunction errorCallback = (KrollFunction)args.get("error"); int majorVersion; int minorVersion; try { PebbleKit.FirmwareVersionInfo versionInfo = PebbleKit.getWatchFWVersion(getApplicationContext()); majorVersion = versionInfo.getMajor(); minorVersion = versionInfo.getMinor(); } catch(Exception e) { Log.w(LCAT, "Could not retrieve version info from Pebble"); HashMap event = new HashMap(); event.put("message", "Could not retrieve version info from Pebble"); errorCallback.call(getKrollObject(), event); return; } Log.d(LCAT, "Pebble FW Major " + majorVersion); Log.d(LCAT, "Pebble FW Minor " + minorVersion); if(successCallback != null) { HashMap versionInfoHash = new HashMap(); versionInfoHash.put("major", majorVersion); versionInfoHash.put("minor", minorVersion); successCallback.call(getKrollObject(), versionInfoHash); } } @Kroll.method public void launchApp(HashMap args) { Log.d(LCAT, "launchApp"); if(!checkWatchConnected()) { Log.w(LCAT, "launchApp: No watch connected"); return; } final KrollFunction successCallback = (KrollFunction)args.get("success"); final KrollFunction errorCallback = (KrollFunction)args.get("error"); try { PebbleKit.startAppOnPebble(getApplicationContext(), uuid); setConnectedCount(0); listenToConnectedWatch(); Log.d(LCAT, "launchApp: Success"); if(successCallback != null) { HashMap event = new HashMap(); event.put("message", "Successfully launched app"); successCallback.call(getKrollObject(), event); } } catch(IllegalArgumentException e) { Log.e(LCAT, "launchApp: Error"); if(errorCallback != null) { errorCallback.call(getKrollObject(), new Object[] {}); } return; } } @Kroll.method public void killApp(HashMap args) { Log.d(LCAT, "killApp"); if(!checkWatchConnected()) { Log.w(LCAT, "killApp: No watch connected"); return; } final KrollFunction successCallback = (KrollFunction)args.get("success"); final KrollFunction errorCallback = (KrollFunction)args.get("error"); try { PebbleKit.closeAppOnPebble(getApplicationContext(), uuid); Log.d(LCAT, "killApp: Success"); if(successCallback != null) { HashMap event = new HashMap(); event.put("message", "Successfully killed app"); successCallback.call(getKrollObject(), event); } } catch(IllegalArgumentException e) { Log.e(LCAT, "killApp: Error"); if(errorCallback != null) { errorCallback.call(getKrollObject(), new Object[] {}); } return; } } @Kroll.method public void sendMessage(HashMap args) { Log.d(LCAT, "sendMessage"); if(!checkWatchConnected()) { Log.w(LCAT, "sendMessage: No watch connected"); return; } final KrollFunction successCallback = (KrollFunction)args.get("success"); final KrollFunction errorCallback = (KrollFunction)args.get("error"); final Object message = args.get("message"); Map<Integer, Object> messageHash = (HashMap<Integer, Object>) message; Iterator<Map.Entry<Integer, Object>> entries = messageHash.entrySet().iterator(); HashMap<String,KrollFunction> callbackArray = new HashMap<String,KrollFunction>(); PebbleDictionary data = new PebbleDictionary(); if(successCallback != null) { callbackArray.put("success", successCallback); } if(errorCallback != null) { callbackArray.put("error", errorCallback); } callbacks.put(transactionCounter, callbackArray); while(entries.hasNext()) { Map.Entry<Integer, Object> entry = entries.next(); if(entry.getValue() instanceof Integer) { data.addInt32((Integer) entry.getKey(), (Integer) entry.getValue()); } else if(entry.getValue() instanceof String) { data.addString((Integer) entry.getKey(), (String) entry.getValue()); } } PebbleKit.sendDataToPebbleWithTransactionId(getApplicationContext(), uuid, data, transactionCounter); transactionCounter++; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package javax.portlet.tck.portlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.Portlet; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletURL; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.tck.beans.JSR286SpecTestCaseDetails; import javax.portlet.tck.beans.TestButton; import javax.portlet.tck.beans.TestLink; import javax.portlet.tck.beans.TestResult; import javax.portlet.tck.beans.TestSetupLink; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS13; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS2; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS6; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS16; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS13A; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS15; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS10; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS11; import static javax.portlet.tck.beans.JSR286SpecTestCaseDetails.V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS15; import static javax.portlet.tck.constants.Constants.THREADID_ATTR; /** * This portlet implements several test cases for the JSR 362 TCK. The test case names are defined * in the /src/main/resources/xml-resources/additionalTCs.xml file. The build process will integrate * the test case names defined in the additionalTCs.xml file into the complete list of test case * names for execution by the driver. * * This is the main portlet for the test cases. If the test cases call for events, this portlet will * initiate the events, but not process them. The processing is done in the companion portlet * AddlRequestTests_SPEC2_11_Render_event * * @author ahmed */ public class AddlRequestTests_SPEC2_11_Render implements Portlet { @Override public void init(PortletConfig config) throws PortletException {} @Override public void destroy() {} @SuppressWarnings("deprecation") @Override public void processAction(ActionRequest portletReq, ActionResponse portletResp) throws PortletException, IOException { String action = portletReq.getParameter("inputval"); if (V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS10.equals(action) && portletReq.getParameter("actionURLTr0") != null && portletReq.getParameter("actionURLTr0").equals("true")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters10 */ /* Details: "The portlet-container must not propagate parameters */ /* received in an action or event request to subsequent render */ /* requests of the portlet" */ portletResp.setRenderParameter("tr0", "true"); } else if (V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS15.equals(action) && portletReq.getParameter("tr3a") != null && portletReq.getParameter("tr3a").equals("true")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters15 */ /* Details: "Render parameters get automatically cleared if the */ /* portlet receives a processAction or processEvent call" */ portletResp.setRenderParameter("tr3b", "true"); } else { portletResp.setRenderParameters(portletReq.getParameterMap()); } long tid = Thread.currentThread().getId(); portletReq.setAttribute(THREADID_ATTR, tid); } @SuppressWarnings("deprecation") @Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { long tid = Thread.currentThread().getId(); portletReq.setAttribute(THREADID_ATTR, tid); PrintWriter writer = portletResp.getWriter(); JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails(); String action = portletReq.getParameter("inputval"); Boolean successTr2 = false, successTr5 = false, successTr6 = false; Boolean successTr7 = false, successTr8 = false, successTr13 = false; // Create result objects for the tests /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters10 */ /* Details: "The portlet-container must not propagate parameters */ /* received in an action or event request to subsequent render */ /* requests of the portlet" */ if (portletReq.getParameter("actionURLTr0") == null && portletReq.getParameter("tr0") != null && "true".equals(portletReq.getParameter("tr0"))) { TestResult tr0 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS10); tr0.setTcSuccess(true); tr0.writeTo(writer); } else { PortletURL aurl = portletResp.createActionURL(); aurl.setParameters(portletReq.getPrivateParameterMap()); aurl.setParameter("actionURLTr0", "true"); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS10, aurl); tb.writeTo(writer); } if (action != null) { if (action.equals("V2AddlRequestTests_SPEC2_11_Render_parameters13")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters13 */ /* Details: "If a portlet receives a render request that is the */ /* result of invoking a render URL targeting this portlet the render */ /* parameters received with the render request must be the parameters */ /* set on the render URL" */ TestResult tr2 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS13); if (portletReq.getParameter("renderURLTr2") != null && portletReq.getParameter("tr2") != null && (portletReq.getParameter("renderURLTr2") .contains("tr2:" + portletReq.getParameter("tr2")) || portletReq.getParameter("renderURLTr2") .contains("tr2=" + portletReq.getParameter("tr2")))) { tr2.setTcSuccess(true); successTr2 = true; } else { tr2.appendTcDetail( "Parameter renderURLTr2 is missing or does not contain tr2 parameter value."); } tr2.writeTo(writer); } else if (action.equals("V2AddlRequestTests_SPEC2_11_Render_parameters2")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters2 */ /* Details: "The parameters the request object returns must be */ /* \"x-www-form-urlencoded\" decoded" */ TestResult tr5 = tcd.getTestResultFailed("V2AddlRequestTests_SPEC2_11_Render_parameters2"); if (portletReq.getParameter("tr5") != null && portletReq.getParameter("tr5").equals("true&<>'")) { tr5.setTcSuccess(true); successTr5 = true; } tr5.writeTo(writer); } else if (action.equals("V2AddlRequestTests_SPEC2_11_Render_parameters6")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters6 */ /* Details: "The getParameterMap method must return an unmodifiable */ /* Map object" */ TestResult tr6 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS6); if (portletReq.getParameterMap().containsKey("inputval") && "V2AddlRequestTests_SPEC2_11_Render_parameters6" .equals(portletReq.getParameterMap().get("inputval")[0])) { String tr6TestStringArray[] = {"Modified Value"}; try { portletReq.getParameterMap().put("inputval", tr6TestStringArray); if ("V2AddlRequestTests_SPEC2_11_Render_parameters6" .equals(portletReq.getParameterMap().get("inputval")[0])) { tr6.setTcSuccess(true); successTr6 = true; } } catch (UnsupportedOperationException e) { tr6.setTcSuccess(true); successTr6 = true; } } tr6.writeTo(writer); } else if (action.equals("V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters15")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters15 */ /* Details: "A map of private parameters can be obtained through the */ /* getPrivateParameterMap method" */ TestResult tr7 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS15); Map<String, String[]> privateParamMap = portletReq.getPrivateParameterMap(); if (privateParamMap != null && privateParamMap.containsKey("tr7") && privateParamMap.get("tr7")[0].equals("true")) { tr7.setTcSuccess(true); successTr7 = true; } tr7.writeTo(writer); } else if (action.equals("V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters16")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters16 */ /* Details: "A map of public parameters can be obtained through the */ /* getPublicParameterMap method" */ TestResult tr8 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS16); if (portletReq.getPublicParameterMap() != null && portletReq.getPublicParameterMap().containsKey("tckPRP3")) { tr8.setTcSuccess(true); successTr8 = true; } else { tr8.appendTcDetail("No public render parameter found."); } tr8.writeTo(writer); } else if (action.equals("V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters13a")) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters13a */ /* Details: "A public render parameter can be deleted using the */ /* removePublicRenderParameter method on the PortletURL" */ TestResult tr13 = tcd.getTestResultFailed("V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters13a"); if (portletReq.getPublicParameterMap() != null && !portletReq.getPublicParameterMap().containsKey("tckPRP3")) { tr13.setTcSuccess(true); successTr13 = true; } else { tr13.appendTcDetail("Render parameter tckPRP3 is not removed."); } tr13.writeTo(writer); } } if (!successTr2) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters13 */ /* Details: "If a portlet receives a render request that is the */ /* result of invoking a render URL targeting this portlet the render */ /* parameters received with the render request must be the parameters */ /* set on the render URL" */ PortletURL rurl = portletResp.createRenderURL(); rurl.setParameters(portletReq.getPrivateParameterMap()); rurl.setParameter("tr2", "true"); rurl.setParameter("renderURLTr2", rurl.toString()); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS13, rurl); tb.writeTo(writer); } if (!successTr5) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters2 */ /* Details: "The parameters the request object returns must be */ /* \"x-www-form-urlencoded\" decoded" */ PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr5", "true&<>'"); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS2, purl); tb.writeTo(writer); } if (!successTr6) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters6 */ /* Details: "The getParameterMap method must return an unmodifiable */ /* Map object" */ PortletURL purl = portletResp.createRenderURL(); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS6, purl); tb.writeTo(writer); } if (!successTr7) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters15 */ /* Details: "A map of private parameters can be obtained through the */ /* getPrivateParameterMap method" */ PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr7", "true"); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS15, purl); tb.writeTo(writer); } if (!successTr8) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters16 */ /* Details: "A map of public parameters can be obtained through the */ /* getPublicParameterMap method" */ if (portletReq.getParameter("tckPRP3") == null) { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tckPRP3", "true"); TestSetupLink tl = new TestSetupLink(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS16, purl); tl.writeTo(writer); } else { PortletURL aurl = portletResp.createRenderURL(); aurl.setParameters(portletReq.getPrivateParameterMap()); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS16, aurl); tb.writeTo(writer); } } if (!successTr13) { /* TestCase: V2AddlRequestTests_SPEC2_11_Render_publicRenderParameters13a */ /* Details: "A public render parameter can be deleted using the */ /* removePublicRenderParameter method on the PortletURL" */ if (portletReq.getParameter("tckPRP3") == null) { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tckPRP3", "true"); TestSetupLink tl = new TestSetupLink(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS13A, purl); tl.writeTo(writer); } else { PortletURL purl = portletResp.createRenderURL(); purl.setParameters(portletReq.getPrivateParameterMap()); purl.removePublicRenderParameter("tckPRP3"); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PUBLICRENDERPARAMETERS13A, purl); tb.writeTo(writer); } } /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters15 */ /* Details: "Render parameters get automatically cleared if the */ /* portlet receives a processAction or processEvent call" */ if (portletReq.getParameter("tr3a") != null) { PortletURL aurl = portletResp.createActionURL(); aurl.setParameters(portletReq.getPrivateParameterMap()); aurl.setParameter("tr3a", portletReq.getParameter("tr3a")); TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS15, aurl); tb.writeTo(writer); } else { if (portletReq.getParameter("tr3b") != null && portletReq.getParameter("tr3b").equals("true")) { TestResult tr3 = tcd.getTestResultFailed(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS15); tr3.setTcSuccess(true); tr3.writeTo(writer); } else { PortletURL purl = portletResp.createRenderURL(); purl.setParameter("tr3a", "true"); TestSetupLink tl = new TestSetupLink(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS15, purl); tl.writeTo(writer); } } /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters11 */ /* Details: "If a portlet receives a render request that is the */ /* result of a client request targeted to another portlet in the */ /* portal page, the parameters should be the same parameters as of */ /* the previous render request from this client" */ { PortletURL rurl = portletResp.createRenderURL(); rurl.setParameters(portletReq.getPrivateParameterMap()); rurl.setParameter("tr1_ready", "true"); TestLink tb = new TestLink(V2ADDLREQUESTTESTS_SPEC2_11_RENDER_PARAMETERS11, rurl); tb.writeTo(writer); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.bcel.classfile; import java.io.DataInput; import java.io.DataOutputStream; import java.io.IOException; import org.apache.bcel.Const; /** * This class represents a inner class attribute, i.e., the class * indices of the inner and outer classes, the name and the attributes * of the inner class. * * @see InnerClasses */ public final class InnerClass implements Cloneable, Node { private int innerClassIndex; private int outerClassIndex; private int innerNameIndex; private int innerAccessFlags; /** * Initialize from another object. */ public InnerClass(final InnerClass c) { this(c.getInnerClassIndex(), c.getOuterClassIndex(), c.getInnerNameIndex(), c .getInnerAccessFlags()); } /** * Construct object from file stream. * @param file Input stream * @throws IOException */ InnerClass(final DataInput file) throws IOException { this(file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), file .readUnsignedShort()); } /** * @param innerClassIndex Class index in constant pool of inner class * @param outerClassIndex Class index in constant pool of outer class * @param innerNameIndex Name index in constant pool of inner class * @param innerAccessFlags Access flags of inner class */ public InnerClass(final int innerClassIndex, final int outerClassIndex, final int innerNameIndex, final int innerAccessFlags) { this.innerClassIndex = innerClassIndex; this.outerClassIndex = outerClassIndex; this.innerNameIndex = innerNameIndex; this.innerAccessFlags = innerAccessFlags; } /** * Called by objects that are traversing the nodes of the tree implicitely * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * * @param v Visitor object */ @Override public void accept( final Visitor v ) { v.visitInnerClass(this); } /** * Dump inner class attribute to file stream in binary format. * * @param file Output file stream * @throws IOException */ public void dump( final DataOutputStream file ) throws IOException { file.writeShort(innerClassIndex); file.writeShort(outerClassIndex); file.writeShort(innerNameIndex); file.writeShort(innerAccessFlags); } /** * @return access flags of inner class. */ public int getInnerAccessFlags() { return innerAccessFlags; } /** * @return class index of inner class. */ public int getInnerClassIndex() { return innerClassIndex; } /** * @return name index of inner class. */ public int getInnerNameIndex() { return innerNameIndex; } /** * @return class index of outer class. */ public int getOuterClassIndex() { return outerClassIndex; } /** * @param innerAccessFlags access flags for this inner class */ public void setInnerAccessFlags( final int innerAccessFlags ) { this.innerAccessFlags = innerAccessFlags; } /** * @param innerClassIndex index into the constant pool for this class */ public void setInnerClassIndex( final int innerClassIndex ) { this.innerClassIndex = innerClassIndex; } /** * @param innerNameIndex index into the constant pool for this class's name */ public void setInnerNameIndex( final int innerNameIndex ) { // TODO unused this.innerNameIndex = innerNameIndex; } /** * @param outerClassIndex index into the constant pool for the owning class */ public void setOuterClassIndex( final int outerClassIndex ) { // TODO unused this.outerClassIndex = outerClassIndex; } /** * @return String representation. */ @Override public String toString() { return "InnerClass(" + innerClassIndex + ", " + outerClassIndex + ", " + innerNameIndex + ", " + innerAccessFlags + ")"; } /** * @return Resolved string representation */ public String toString( final ConstantPool constantPool ) { String outer_class_name; String inner_name; String inner_class_name = constantPool.getConstantString(innerClassIndex, Const.CONSTANT_Class); inner_class_name = Utility.compactClassName(inner_class_name, false); if (outerClassIndex != 0) { outer_class_name = constantPool.getConstantString(outerClassIndex, Const.CONSTANT_Class); outer_class_name = " of class " + Utility.compactClassName(outer_class_name, false); } else { outer_class_name = ""; } if (innerNameIndex != 0) { inner_name = ((ConstantUtf8) constantPool.getConstant(innerNameIndex, Const.CONSTANT_Utf8)).getBytes(); } else { inner_name = "(anonymous)"; } String access = Utility.accessToString(innerAccessFlags, true); access = access.isEmpty() ? "" : access + " "; return " " + access + inner_name + "=class " + inner_class_name + outer_class_name; } /** * @return deep copy of this object */ public InnerClass copy() { try { return (InnerClass) clone(); } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.descriptor.web; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; /** * Representation of a handler reference for a web service, as * represented in a <code>&lt;handler&gt;</code> element in the * deployment descriptor. * * @author Fabien Carrion */ public class ContextHandler extends ResourceBase { private static final long serialVersionUID = 1L; // ------------------------------------------------------------- Properties /** * The Handler reference class. */ private String handlerclass = null; public String getHandlerclass() { return (this.handlerclass); } public void setHandlerclass(String handlerclass) { this.handlerclass = handlerclass; } /** * A list of QName specifying the SOAP Headers the handler will work on. * -namespace and locapart values must be found inside the WSDL. * * A service-qname is composed by a namespaceURI and a localpart. * * soapHeader[0] : namespaceURI * soapHeader[1] : localpart */ private final HashMap<String, String> soapHeaders = new HashMap<>(); public Iterator<String> getLocalparts() { return soapHeaders.keySet().iterator(); } public String getNamespaceuri(String localpart) { return soapHeaders.get(localpart); } public void addSoapHeaders(String localpart, String namespaceuri) { soapHeaders.put(localpart, namespaceuri); } /** * Set a configured property. */ public void setProperty(String name, String value) { this.setProperty(name, (Object) value); } /** * The soapRole. */ private final ArrayList<String> soapRoles = new ArrayList<>(); public String getSoapRole(int i) { return this.soapRoles.get(i); } public int getSoapRolesSize() { return this.soapRoles.size(); } public void addSoapRole(String soapRole) { this.soapRoles.add(soapRole); } /** * The portName. */ private final ArrayList<String> portNames = new ArrayList<>(); public String getPortName(int i) { return this.portNames.get(i); } public int getPortNamesSize() { return this.portNames.size(); } public void addPortName(String portName) { this.portNames.add(portName); } // --------------------------------------------------------- Public Methods /** * Return a String representation of this object. */ @Override public String toString() { StringBuilder sb = new StringBuilder("ContextHandler["); sb.append("name="); sb.append(getName()); if (handlerclass != null) { sb.append(", class="); sb.append(handlerclass); } if (this.soapHeaders != null) { sb.append(", soap-headers="); sb.append(this.soapHeaders); } if (this.getSoapRolesSize() > 0) { sb.append(", soap-roles="); sb.append(soapRoles); } if (this.getPortNamesSize() > 0) { sb.append(", port-name="); sb.append(portNames); } if (this.listProperties() != null) { sb.append(", init-param="); sb.append(this.listProperties()); } sb.append("]"); return (sb.toString()); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((handlerclass == null) ? 0 : handlerclass.hashCode()); result = prime * result + ((portNames == null) ? 0 : portNames.hashCode()); result = prime * result + ((soapHeaders == null) ? 0 : soapHeaders.hashCode()); result = prime * result + ((soapRoles == null) ? 0 : soapRoles.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } ContextHandler other = (ContextHandler) obj; if (handlerclass == null) { if (other.handlerclass != null) { return false; } } else if (!handlerclass.equals(other.handlerclass)) { return false; } if (portNames == null) { if (other.portNames != null) { return false; } } else if (!portNames.equals(other.portNames)) { return false; } if (soapHeaders == null) { if (other.soapHeaders != null) { return false; } } else if (!soapHeaders.equals(other.soapHeaders)) { return false; } if (soapRoles == null) { if (other.soapRoles != null) { return false; } } else if (!soapRoles.equals(other.soapRoles)) { return false; } return true; } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.ml.dataframe.analyses; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.Version; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.DeprecationHandler; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.search.SearchModule; import org.elasticsearch.xpack.core.ml.AbstractBWCSerializationTestCase; import org.elasticsearch.xpack.core.ml.inference.MlInferenceNamedXContentProvider; import org.elasticsearch.xpack.core.ml.inference.preprocessing.FrequencyEncodingTests; import org.elasticsearch.xpack.core.ml.inference.preprocessing.OneHotEncodingTests; import org.elasticsearch.xpack.core.ml.inference.preprocessing.PreProcessor; import org.elasticsearch.xpack.core.ml.inference.preprocessing.TargetMeanEncodingTests; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceConfig; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.RegressionConfig; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; public class RegressionTests extends AbstractBWCSerializationTestCase<Regression> { private static final BoostedTreeParams BOOSTED_TREE_PARAMS = BoostedTreeParams.builder().build(); @Override protected Regression doParseInstance(XContentParser parser) throws IOException { return Regression.fromXContent(parser, false); } @Override protected Regression createTestInstance() { return createRandom(); } @Override protected NamedXContentRegistry xContentRegistry() { List<NamedXContentRegistry.Entry> namedXContent = new ArrayList<>(); namedXContent.addAll(new MlInferenceNamedXContentProvider().getNamedXContentParsers()); namedXContent.addAll(new SearchModule(Settings.EMPTY, Collections.emptyList()).getNamedXContents()); return new NamedXContentRegistry(namedXContent); } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { List<NamedWriteableRegistry.Entry> entries = new ArrayList<>(); entries.addAll(new MlInferenceNamedXContentProvider().getNamedWriteables()); return new NamedWriteableRegistry(entries); } public static Regression createRandom() { return createRandom(BoostedTreeParamsTests.createRandom()); } private static Regression createRandom(BoostedTreeParams boostedTreeParams) { String dependentVariableName = randomAlphaOfLength(10); String predictionFieldName = randomBoolean() ? null : randomAlphaOfLength(10); Double trainingPercent = randomBoolean() ? null : randomDoubleBetween(0.0, 100.0, false); Long randomizeSeed = randomBoolean() ? null : randomLong(); Regression.LossFunction lossFunction = randomBoolean() ? null : randomFrom(Regression.LossFunction.values()); Double lossFunctionParameter = randomBoolean() ? null : randomDoubleBetween(0.0, Double.MAX_VALUE, false); return new Regression(dependentVariableName, boostedTreeParams, predictionFieldName, trainingPercent, randomizeSeed, lossFunction, lossFunctionParameter, randomBoolean() ? null : Stream.generate(() -> randomFrom(FrequencyEncodingTests.createRandom(true), OneHotEncodingTests.createRandom(true), TargetMeanEncodingTests.createRandom(true))) .limit(randomIntBetween(0, 5)) .collect(Collectors.toList())); } public static Regression mutateForVersion(Regression instance, Version version) { return new Regression(instance.getDependentVariable(), BoostedTreeParamsTests.mutateForVersion(instance.getBoostedTreeParams(), version), instance.getPredictionFieldName(), instance.getTrainingPercent(), instance.getRandomizeSeed(), instance.getLossFunction(), instance.getLossFunctionParameter(), version.onOrAfter(Version.V_7_10_0) ? instance.getFeatureProcessors() : Collections.emptyList()); } @Override protected void assertOnBWCObject(Regression bwcSerializedObject, Regression testInstance, Version version) { if (version.onOrAfter(Version.V_7_6_0)) { super.assertOnBWCObject(bwcSerializedObject, testInstance, version); return; } Regression newBwc = new Regression(bwcSerializedObject.getDependentVariable(), bwcSerializedObject.getBoostedTreeParams(), bwcSerializedObject.getPredictionFieldName(), bwcSerializedObject.getTrainingPercent(), 42L, bwcSerializedObject.getLossFunction(), bwcSerializedObject.getLossFunctionParameter(), bwcSerializedObject.getFeatureProcessors()); Regression newInstance = new Regression(testInstance.getDependentVariable(), testInstance.getBoostedTreeParams(), testInstance.getPredictionFieldName(), testInstance.getTrainingPercent(), 42L, testInstance.getLossFunction(), testInstance.getLossFunctionParameter(), testInstance.getFeatureProcessors()); super.assertOnBWCObject(newBwc, newInstance, version); } @Override protected Regression mutateInstanceForVersion(Regression instance, Version version) { return mutateForVersion(instance, version); } @Override protected Writeable.Reader<Regression> instanceReader() { return Regression::new; } public void testDeserialization() throws IOException { String toDeserialize = "{\n" + " \"dependent_variable\": \"FlightDelayMin\",\n" + " \"feature_processors\": [\n" + " {\n" + " \"one_hot_encoding\": {\n" + " \"field\": \"OriginWeather\",\n" + " \"hot_map\": {\n" + " \"sunny_col\": \"Sunny\",\n" + " \"clear_col\": \"Clear\",\n" + " \"rainy_col\": \"Rain\"\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"one_hot_encoding\": {\n" + " \"field\": \"DestWeather\",\n" + " \"hot_map\": {\n" + " \"dest_sunny_col\": \"Sunny\",\n" + " \"dest_clear_col\": \"Clear\",\n" + " \"dest_rainy_col\": \"Rain\"\n" + " }\n" + " }\n" + " },\n" + " {\n" + " \"frequency_encoding\": {\n" + " \"field\": \"OriginWeather\",\n" + " \"feature_name\": \"mean\",\n" + " \"frequency_map\": {\n" + " \"Sunny\": 0.8,\n" + " \"Rain\": 0.2\n" + " }\n" + " }\n" + " }\n" + " ]\n" + " }" + ""; try(XContentParser parser = XContentHelper.createParser(xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(toDeserialize), XContentType.JSON)) { Regression parsed = Regression.fromXContent(parser, false); assertThat(parsed.getDependentVariable(), equalTo("FlightDelayMin")); for (PreProcessor preProcessor : parsed.getFeatureProcessors()) { assertThat(preProcessor.isCustom(), is(true)); } } } public void testConstructor_GivenTrainingPercentIsZero() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 0.0, randomLong(), Regression.LossFunction.MSE, null, null)); assertThat(e.getMessage(), equalTo("[training_percent] must be a positive double in (0, 100]")); } public void testConstructor_GivenTrainingPercentIsLessThanZero() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", -0.01, randomLong(), Regression.LossFunction.MSE, null, null)); assertThat(e.getMessage(), equalTo("[training_percent] must be a positive double in (0, 100]")); } public void testConstructor_GivenTrainingPercentIsGreaterThan100() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 100.0001, randomLong(), Regression.LossFunction.MSE, null, null)); assertThat(e.getMessage(), equalTo("[training_percent] must be a positive double in (0, 100]")); } public void testConstructor_GivenLossFunctionParameterIsZero() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 100.0, randomLong(), Regression.LossFunction.MSE, 0.0, null)); assertThat(e.getMessage(), equalTo("[loss_function_parameter] must be a positive double")); } public void testConstructor_GivenLossFunctionParameterIsNegative() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Regression("foo", BOOSTED_TREE_PARAMS, "result", 100.0, randomLong(), Regression.LossFunction.MSE, -1.0, null)); assertThat(e.getMessage(), equalTo("[loss_function_parameter] must be a positive double")); } public void testGetPredictionFieldName() { Regression regression = new Regression( "foo", BOOSTED_TREE_PARAMS, "result", 50.0, randomLong(), Regression.LossFunction.MSE, 1.0, null); assertThat(regression.getPredictionFieldName(), equalTo("result")); regression = new Regression("foo", BOOSTED_TREE_PARAMS, null, 50.0, randomLong(), Regression.LossFunction.MSE, null, null); assertThat(regression.getPredictionFieldName(), equalTo("foo_prediction")); } public void testGetTrainingPercent() { Regression regression = new Regression("foo", BOOSTED_TREE_PARAMS, "result", 50.0, randomLong(), Regression.LossFunction.MSE, 1.0, null); assertThat(regression.getTrainingPercent(), equalTo(50.0)); // Boundary condition: training_percent == 1.0 regression = new Regression("foo", BOOSTED_TREE_PARAMS, "result", 1.0, randomLong(), Regression.LossFunction.MSE, null, null); assertThat(regression.getTrainingPercent(), equalTo(1.0)); // Boundary condition: training_percent == 100.0 regression = new Regression("foo", BOOSTED_TREE_PARAMS, "result", 100.0, randomLong(), Regression.LossFunction.MSE, null, null); assertThat(regression.getTrainingPercent(), equalTo(100.0)); // training_percent == null, default applied regression = new Regression("foo", BOOSTED_TREE_PARAMS, "result", null, randomLong(), Regression.LossFunction.MSE, null, null); assertThat(regression.getTrainingPercent(), equalTo(100.0)); } public void testGetParams_ShouldIncludeBoostedTreeParams() { int maxTrees = randomIntBetween(1, 100); Regression regression = new Regression("foo", BoostedTreeParams.builder().setMaxTrees(maxTrees).build(), null, 100.0, 0L, Regression.LossFunction.MSE, null, null); Map<String, Object> params = regression.getParams(null); assertThat(params.size(), equalTo(5)); assertThat(params.get("dependent_variable"), equalTo("foo")); assertThat(params.get("prediction_field_name"), equalTo("foo_prediction")); assertThat(params.get("max_trees"), equalTo(maxTrees)); assertThat(params.get("training_percent"), equalTo(100.0)); assertThat(params.get("loss_function"), equalTo("mse")); } public void testGetParams_GivenRandomWithoutBoostedTreeParams() { Regression regression = createRandom(BoostedTreeParams.builder().build()); Map<String, Object> params = regression.getParams(null); int expectedParamsCount = 4 + (regression.getLossFunctionParameter() == null ? 0 : 1) + (regression.getFeatureProcessors().isEmpty() ? 0 : 1); assertThat(params.size(), equalTo(expectedParamsCount)); assertThat(params.get("dependent_variable"), equalTo(regression.getDependentVariable())); assertThat(params.get("prediction_field_name"), equalTo(regression.getPredictionFieldName())); assertThat(params.get("training_percent"), equalTo(regression.getTrainingPercent())); assertThat(params.get("loss_function"), equalTo(regression.getLossFunction().toString())); if (regression.getLossFunctionParameter() == null) { assertThat(params.containsKey("loss_function_parameter"), is(false)); } else { assertThat(params.get("loss_function_parameter"), equalTo(regression.getLossFunctionParameter())); } } public void testRequiredFieldsIsNonEmpty() { assertThat(createTestInstance().getRequiredFields(), is(not(empty()))); } public void testFieldCardinalityLimitsIsEmpty() { assertThat(createTestInstance().getFieldCardinalityConstraints(), is(empty())); } public void testGetResultMappings() { Map<String, Object> resultMappings = new Regression("foo").getResultMappings("results", null); assertThat(resultMappings, hasEntry("results.foo_prediction", Collections.singletonMap("type", "double"))); assertThat(resultMappings, hasEntry("results.feature_importance", Regression.FEATURE_IMPORTANCE_MAPPING)); assertThat(resultMappings, hasEntry("results.is_training", Collections.singletonMap("type", "boolean"))); } public void testGetStateDocId() { Regression regression = createRandom(); assertThat(regression.persistsState(), is(true)); String randomId = randomAlphaOfLength(10); assertThat(regression.getStateDocIdPrefix(randomId), equalTo(randomId + "_regression_state#")); } public void testExtractJobIdFromStateDoc() { assertThat(Regression.extractJobIdFromStateDoc("foo_bar-1_regression_state#1"), equalTo("foo_bar-1")); assertThat(Regression.extractJobIdFromStateDoc("noop"), is(nullValue())); } public void testToXContent_GivenVersionBeforeRandomizeSeedWasIntroduced() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", "7.5.0"))); String json = Strings.toString(builder); assertThat(json, not(containsString("randomize_seed"))); } } public void testToXContent_GivenVersionAfterRandomizeSeedWasIntroduced() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", Version.CURRENT.toString()))); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testToXContent_GivenVersionIsNull() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", null))); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testToXContent_GivenEmptyParams() throws IOException { Regression regression = createRandom(); assertThat(regression.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { regression.toXContent(builder, ToXContent.EMPTY_PARAMS); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testInferenceConfig() { Regression regression = createRandom(); InferenceConfig inferenceConfig = regression.inferenceConfig(null); assertThat(inferenceConfig, instanceOf(RegressionConfig.class)); RegressionConfig regressionConfig = (RegressionConfig) inferenceConfig; assertThat(regressionConfig.getResultsField(), equalTo(regression.getPredictionFieldName())); Integer expectedNumTopFeatureImportanceValues = regression.getBoostedTreeParams().getNumTopFeatureImportanceValues() == null ? 0 : regression.getBoostedTreeParams().getNumTopFeatureImportanceValues(); assertThat(regressionConfig.getNumTopFeatureImportanceValues(), equalTo(expectedNumTopFeatureImportanceValues)); } }
/* * Copyright 2017 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.truth.Truth.assertThat; import static com.google.javascript.jscomp.testing.ScopeSubject.assertScope; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** A tests for {@link IncrementalScopeCreator}. */ @RunWith(JUnit4.class) public final class IncrementalScopeCreatorTest { @Test public void testMemoization() { List<SourceFile> externs = ImmutableList.of( SourceFile.fromCode("externs.js", "var ext")); List<SourceFile> srcs = ImmutableList.of( SourceFile.fromCode("testcode1.js", "var a; var b; function foo() { var inside = 1; }"), SourceFile.fromCode("testcode2.js", "var x;")); Compiler compiler = initCompiler(externs, srcs); IncrementalScopeCreator creator = IncrementalScopeCreator.getInstance(compiler).freeze(); Node root1 = compiler.getRoot(); Scope scopeA = creator.createScope(root1, null); assertThat(creator.createScope(root1, null)).isSameInstanceAs(scopeA); IncrementalScopeCreator.getInstance(compiler).thaw(); IncrementalScopeCreator.getInstance(compiler).freeze(); assertThat(creator.createScope(root1, null)).isSameInstanceAs(scopeA); try { Node root2 = IR.root(); creator.createScope(root2, null); throw new AssertionError(); } catch (IllegalArgumentException expected) { assertThat(expected) .hasMessageThat() .contains("the shared persistent scope must always " + "be root at the tip of the AST"); } } @Test public void testParialGlobalScopeRefresh() { List<SourceFile> externs = ImmutableList.of( SourceFile.fromCode("externs.js", "var ext")); List<SourceFile> srcs = ImmutableList.of( SourceFile.fromCode("testcode1.js", "var a; var b; function foo() { var inside = 1; }"), SourceFile.fromCode("testcode2.js", "var x;")); Compiler compiler = initCompiler(externs, srcs); IncrementalScopeCreator creator = IncrementalScopeCreator.getInstance(compiler).freeze(); Node root = compiler.getRoot(); Node fnFoo = findDecl(root, "foo"); checkState(fnFoo.isFunction()); Scope globalScope = creator.createScope(root, null); Scope globalFunction = creator.createScope(fnFoo, globalScope); // When refreshing a local scope, the Scope object is preserved but the Var objects are // recreated, so we need to inspect a Var in the scope to see if it has been freshed or not. Var inside = globalFunction.getVar("inside"); assertScope(globalScope).declares("a"); assertScope(globalScope).declares("b"); assertScope(globalScope).declares("x"); assertScope(globalScope).declares("ext"); assertScope(globalScope).doesNotDeclare("nonexistant"); // Make a change that affects the global scope (and report it) removeFirstDecl(compiler, compiler.getRoot(), "a"); Scope globalScope2 = creator.createScope(compiler.getRoot(), null); assertThat(globalScope2).isSameInstanceAs(globalScope); // unchanged local scopes should be preserved assertThat(creator.createScope(fnFoo, globalScope)).isSameInstanceAs(globalFunction); assertThat(globalFunction.getVar("inside")).isSameInstanceAs(inside); assertScope(globalScope2).declares("a"); // still declared, scope creator is frozen assertScope(globalScope2).declares("b"); assertScope(globalScope2).declares("x"); assertScope(globalScope2).declares("ext"); assertScope(globalScope2).doesNotDeclare("nonexistant"); // Allow the scopes to be updated by calling "thaw" and "freeze" IncrementalScopeCreator.getInstance(compiler).thaw(); IncrementalScopeCreator.getInstance(compiler).freeze(); Scope globalScope3 = creator.createScope(compiler.getRoot(), null); assertThat(globalScope3).isSameInstanceAs(globalScope); // unchanged local scopes should be preserved assertThat(creator.createScope(fnFoo, globalScope)).isSameInstanceAs(globalFunction); assertThat(globalFunction.getVar("inside")).isSameInstanceAs(inside); assertScope(globalScope3).doesNotDeclare("a"); // no declared, scope creator has refreshed assertScope(globalScope3).declares("b"); assertScope(globalScope3).declares("x"); assertScope(globalScope3).declares("ext"); assertScope(globalScope3).doesNotDeclare("nonexistant"); IncrementalScopeCreator.getInstance(compiler).thaw(); } @Test public void testPartialGlobalScopeRefreshWithMove() { // This test verifies that when a variable declarations moves between script, the // original script correctly "forgets" that the moved variables was associated with // it. If this were not the case, invalidating the original script would // undeclare a variable and readding the variables when rescanning the script would not // readd it. List<SourceFile> externs = ImmutableList.of( SourceFile.fromCode("externs.js", "")); List<SourceFile> srcs = ImmutableList.of( SourceFile.fromCode("testcode1.js", "var a; var b;"), SourceFile.fromCode("testcode2.js", "var x; var y;")); Compiler compiler = initCompiler(externs, srcs); IncrementalScopeCreator creator = IncrementalScopeCreator.getInstance(compiler).freeze(); Node root = compiler.getRoot(); Scope globalScope = creator.createScope(root, null); assertScope(globalScope).declares("a").directly(); assertScope(globalScope).declares("b").directly(); assertScope(globalScope).declares("x").directly(); assertScope(globalScope).declares("y").directly(); assertScope(globalScope).doesNotDeclare("nonexistant"); Node script1 = checkNotNull(NodeUtil.getEnclosingScript(findDecl(root, "a"))); Node script2 = checkNotNull(NodeUtil.getEnclosingScript(findDecl(root, "x"))); Node varB = checkNotNull(findDecl(root, "b")); // Move B to from script1 to script2 varB.detach(); script2.addChildToBack(varB); compiler.reportChangeToChangeScope(script1); compiler.reportChangeToChangeScope(script2); // Allow the scopes to update by "thaw" and "freeze" again. creator.thaw(); creator.freeze(); globalScope = creator.createScope(root, null); assertScope(globalScope).declares("a").directly(); assertScope(globalScope).declares("b").directly(); assertScope(globalScope).declares("x").directly(); assertScope(globalScope).declares("y").directly(); assertScope(globalScope).doesNotDeclare("nonexistant"); compiler.reportChangeToChangeScope(script1); // invalidate the original scope. // Allow the scopes to update by "thaw" and "freeze" again. creator.thaw(); creator.freeze(); globalScope = creator.createScope(root, null); assertScope(globalScope).declares("a").directly(); assertScope(globalScope).declares("b").directly(); assertScope(globalScope).declares("x").directly(); assertScope(globalScope).declares("y").directly(); assertScope(globalScope).doesNotDeclare("nonexistant"); creator.thaw(); } @Test public void testRefreshedGlobalScopeWithRedeclaration() { List<SourceFile> externs = ImmutableList.of( SourceFile.fromCode("externs.js", "")); List<SourceFile> srcs = ImmutableList.of( SourceFile.fromCode("testcode1.js", "var a; var b;"), SourceFile.fromCode("testcode2.js", "var a;")); Compiler compiler = initCompiler(externs, srcs); IncrementalScopeCreator creator = IncrementalScopeCreator.getInstance(compiler).freeze(); Node root = compiler.getRoot(); Scope globalScope = creator.createScope(root, null); assertScope(globalScope).declares("a"); assertScope(globalScope).declares("b"); removeFirstDecl(compiler, compiler.getRoot(), "a"); // leaves the second declaration removeFirstDecl(compiler, compiler.getRoot(), "b"); // Allow the scopes to be updated by calling "thaw" and "freeze" IncrementalScopeCreator.getInstance(compiler).thaw(); IncrementalScopeCreator.getInstance(compiler).freeze(); Scope globalScope2 = creator.createScope(compiler.getRoot(), null); assertThat(globalScope2).isSameInstanceAs(globalScope); assertScope(globalScope2).declares("a"); // still declared in second file assertScope(globalScope2).doesNotDeclare("b"); IncrementalScopeCreator.getInstance(compiler).thaw(); } @Test public void testValidScopeReparenting() { List<SourceFile> externs = ImmutableList.of( SourceFile.fromCode("externs.js", "var ext")); List<SourceFile> srcs = ImmutableList.of( SourceFile.fromCode("testcode1.js", "var a; var b; " + " { function foo() { var inside = 1; } }"), SourceFile.fromCode("testcode2.js", "var x;")); Compiler compiler = initCompiler(externs, srcs); IncrementalScopeCreator creator = IncrementalScopeCreator.getInstance(compiler).freeze(); Node root = compiler.getRoot(); Node fnFoo = findDecl(root, "foo"); checkState(fnFoo.isFunction()); Node block = fnFoo.getParent(); checkState(block.isBlock()); Scope globalScope1 = creator.createScope(root, null); Scope blockScope1 = creator.createScope(block, globalScope1); Scope fnScope1 = creator.createScope(fnFoo, blockScope1); assertThat(fnScope1.getDepth()).isSameInstanceAs(blockScope1.getDepth() + 1); assertThat(fnScope1.getParent()).isSameInstanceAs(blockScope1); // When refreshing a local scope, the Scope object is preserved but the Var objects are // recreated, so we need to inspect a Var in the scope to see if it has been freshed or not. Var inside1 = fnScope1.getVar("inside"); compiler.reportChangeToEnclosingScope(block); block.replaceWith(fnFoo.detach()); IncrementalScopeCreator.getInstance(compiler).thaw(); IncrementalScopeCreator.getInstance(compiler).freeze(); Scope globalScope2 = creator.createScope(root, null); Scope fnScope2 = creator.createScope(fnFoo, globalScope2); assertThat(fnScope2).isSameInstanceAs(fnScope1); assertThat(fnScope2.getParent()).isSameInstanceAs(globalScope2); assertThat(fnScope2.getDepth()).isSameInstanceAs(globalScope2.getDepth() + 1); assertThat(fnScope2.getVar("inside")).isSameInstanceAs(inside1); IncrementalScopeCreator.getInstance(compiler).thaw(); } private void removeFirstDecl(Compiler compiler, Node n, String name) { Node decl = findDecl(n, name); compiler.reportChangeToEnclosingScope(decl); decl.detach(); } private Node findDecl(Node n, String name) { Node result = NodeUtil.findPreorder(n, new NodeUtil.MatchNameNode(name), Predicates.<Node>alwaysTrue()); return result.getParent(); } Compiler initCompiler(List<SourceFile> externs, List<SourceFile> srcs) { Compiler compiler = new Compiler(); CompilerOptions options = new CompilerOptions(); compiler.init(externs, srcs, options); compiler.parseInputs(); checkState(!compiler.hasErrors()); return compiler; } }
package in.twizmwaz.cardinal.module.modules.filter; import in.twizmwaz.cardinal.GameHandler; import in.twizmwaz.cardinal.match.Match; import in.twizmwaz.cardinal.module.BuilderData; import in.twizmwaz.cardinal.module.ModuleBuilder; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.ModuleLoadTime; import in.twizmwaz.cardinal.module.modules.filter.parsers.BlockFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.CauseFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.ClassFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.EntityFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.GenericFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.ItemFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.KillstreakFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.MobFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.ObjectiveFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.RandomFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.SpawnFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.TeamFilterParser; import in.twizmwaz.cardinal.module.modules.filter.parsers.TimeFilterParser; import in.twizmwaz.cardinal.module.modules.filter.type.BlockFilter; import in.twizmwaz.cardinal.module.modules.filter.type.CarryingFilter; import in.twizmwaz.cardinal.module.modules.filter.type.CauseFilter; import in.twizmwaz.cardinal.module.modules.filter.type.ClassFilter; import in.twizmwaz.cardinal.module.modules.filter.type.CrouchingFilter; import in.twizmwaz.cardinal.module.modules.filter.type.EntityFilter; import in.twizmwaz.cardinal.module.modules.filter.type.FlyingAbilityFilter; import in.twizmwaz.cardinal.module.modules.filter.type.FlyingFilter; import in.twizmwaz.cardinal.module.modules.filter.type.HoldingFilter; import in.twizmwaz.cardinal.module.modules.filter.type.KillStreakFilter; import in.twizmwaz.cardinal.module.modules.filter.type.MobFilter; import in.twizmwaz.cardinal.module.modules.filter.type.ObjectiveFilter; import in.twizmwaz.cardinal.module.modules.filter.type.RandomFilter; import in.twizmwaz.cardinal.module.modules.filter.type.SpawnFilter; import in.twizmwaz.cardinal.module.modules.filter.type.TeamFilter; import in.twizmwaz.cardinal.module.modules.filter.type.TimeFilter; import in.twizmwaz.cardinal.module.modules.filter.type.VoidFilter; import in.twizmwaz.cardinal.module.modules.filter.type.WearingFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllBlockFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllEntitiesFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllEventFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllMobFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllPlayerFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllSpawnFilter; import in.twizmwaz.cardinal.module.modules.filter.type.constant.AllWorldFilter; import in.twizmwaz.cardinal.module.modules.filter.type.logic.AllFilter; import in.twizmwaz.cardinal.module.modules.filter.type.logic.AnyFilter; import in.twizmwaz.cardinal.module.modules.filter.type.logic.NotFilter; import in.twizmwaz.cardinal.module.modules.filter.type.logic.OneFilter; import in.twizmwaz.cardinal.module.modules.filter.type.old.AllowFilter; import in.twizmwaz.cardinal.module.modules.filter.type.old.DenyFilter; import org.jdom2.Document; import org.jdom2.Element; @BuilderData(load = ModuleLoadTime.EARLY) public class FilterModuleBuilder implements ModuleBuilder { /** * @param element Element to parse * @param document Document to find filter in case the given filter is a reference * @return The filter based upon the given element */ public static FilterModule getFilter(Element element, Document document) { switch (element.getName().toLowerCase()) { case "block": return new BlockFilter(new BlockFilterParser(element)); case "carrying": return new CarryingFilter(new ItemFilterParser(element)); case "cause": return new CauseFilter(new CauseFilterParser(element)); case "class": return new ClassFilter(new ClassFilterParser(element)); case "crouching": return new CrouchingFilter(new FilterParser(element)); case "entity": return new EntityFilter(new EntityFilterParser(element)); case "can-fly": return new FlyingAbilityFilter(new FilterParser(element)); case "flying": return new FlyingFilter(new FilterParser(element)); case "holding": return new HoldingFilter(new ItemFilterParser(element)); case "kill-streak": return new KillStreakFilter(new KillstreakFilterParser(element)); case "mob": return new MobFilter(new MobFilterParser(element)); case "objective": return new ObjectiveFilter(new ObjectiveFilterParser(element)); case "random": return new RandomFilter(new RandomFilterParser(element)); case "spawn": return new SpawnFilter(new SpawnFilterParser(element)); case "team": return new TeamFilter((new TeamFilterParser(element))); case "time": return new TimeFilter(new TimeFilterParser(element)); case "void": return new VoidFilter(new GenericFilterParser(element)); case "wearing": return new WearingFilter(new ItemFilterParser(element)); case "all": return new AllFilter(new ChildrenFilterParser(element)); case "any": return new AnyFilter(new ChildrenFilterParser(element)); case "not": return new NotFilter(new ChildrenFilterParser(element)); case "one": return new OneFilter(new ChildrenFilterParser(element)); case "allow": return new AllowFilter(new ChildrenFilterParser(element)); case "deny": return new DenyFilter(new ChildrenFilterParser(element)); case "filter": if (element.getChildren().size() > 0) { if (element.getChildren().size() > 1) { return new AllFilter(new ChildrenFilterParser(element)); } else { return getFilter(element.getChildren().get(0)); } } else { switch (element.getAttributeValue("name").toLowerCase()) { case "allow-all": return new AllEventFilter("allow-all", true); case "deny-all": return new AllEventFilter("deny-all", false); case "allow-players": return new AllPlayerFilter("allow-players", true); case "deny-players": return new AllPlayerFilter("deny-players", false); case "allow-blocks": return new AllBlockFilter("allow-blocks", true); case "deny-blocks": return new AllBlockFilter("deny-blocks", false); case "allow-world": return new AllWorldFilter("allow-world", true); case "deny-world": return new AllWorldFilter("deny-world", false); case "allow-spawns": return new AllSpawnFilter("allow-spawns", true); case "deny-spawns": return new AllSpawnFilter("deny-spawns", false); case "allow-entities": return new AllEntitiesFilter("allow-entities", true); case "deny-entities": return new AllEntitiesFilter("deny-entities", false); case "allow-mobs": return new AllMobFilter("allow-mobs", true); case "deny-mobs": return new AllMobFilter("deny-mobs", false); case "allow": return new AllowFilter(new ChildrenFilterParser(element)); case "deny": return new DenyFilter(new ChildrenFilterParser(element)); default: if (element.getAttributeValue("name") != null) { for (Element filterElement : document.getRootElement().getChildren("filters")) { for (Element givenFilter : filterElement.getChildren()) { if (givenFilter.getAttributeValue("name").equalsIgnoreCase(element.getAttributeValue("name"))) return getFilter(givenFilter.getChildren().get(0)); } } } else { return getFilter(element.getChildren().get(0)); } } } default: return null; } } /** * This method will default the document to the document of the current match (possibly buggy) * * @param element Element to parse * @return The filter based upon the given element */ public static FilterModule getFilter(Element element) { return getFilter(element, GameHandler.getGameHandler().getMatch().getDocument()); } /** * Gets a loaded filter by the given name * * @param string * @return */ public static FilterModule getFilter(String string) { for (FilterModule filterModule : GameHandler.getGameHandler().getMatch().getModules().getModules(FilterModule.class)) { if (string.equalsIgnoreCase(filterModule.getName())) return filterModule; } return null; } @Override public ModuleCollection<FilterModule> load(Match match) { match.getModules().add(new AllEventFilter("allow-all", true)); match.getModules().add(new AllEventFilter("deny-all", false)); match.getModules().add(new AllPlayerFilter("allow-players", true)); match.getModules().add(new AllPlayerFilter("deny-players", false)); match.getModules().add(new AllBlockFilter("allow-blocks", true)); match.getModules().add(new AllBlockFilter("deny-blocks", false)); match.getModules().add(new AllWorldFilter("allow-world", true)); match.getModules().add(new AllWorldFilter("deny-world", false)); match.getModules().add(new AllSpawnFilter("allow-spawns", true)); match.getModules().add(new AllSpawnFilter("deny-spawns", false)); match.getModules().add(new AllEntitiesFilter("allow-entities", true)); match.getModules().add(new AllEntitiesFilter("deny-entities", false)); match.getModules().add(new AllMobFilter("allow-mobs", true)); match.getModules().add(new AllMobFilter("deny-mobs", false)); for (Element element : match.getDocument().getRootElement().getChildren("filters")) { for (Element filter : element.getChildren("filter")) { if (filter.getChildren().size() > 1) { match.getModules().add(new AllFilter(new ChildrenFilterParser(filter))); } else { match.getModules().add(getFilter(filter.getChildren().get(0))); } } } return new ModuleCollection<>(); } }
package com.parse.starter; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import java.io.ByteArrayOutputStream; /** * Created by Jizhizi Li on 15/09/2015. */ public class PhotoFilters extends AppCompatActivity { private ImageView filterImage; private Bitmap resultBitmap; private Bitmap originalBitmap; private Button laststep; private Button nextstep; private ImageButton filterInvert; private ImageButton filterGray; private ImageButton filterOld; private ImageButton filterOriginal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo_filters); filterImage = (ImageView) findViewById(R.id.filterimage); filterInvert = (ImageButton) findViewById(R.id.invert); filterGray = (ImageButton) findViewById(R.id.gray); filterOld = (ImageButton) findViewById(R.id.old); laststep = (Button) findViewById(R.id.laststep); nextstep = (Button) findViewById(R.id.nextstep); filterOriginal = (ImageButton)findViewById(R.id.original); //<------------------------Redeving image from last intent--------------------------> if (getIntent().hasExtra("byteArray")) { Bitmap b = BitmapFactory.decodeByteArray( getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length); filterImage.setImageBitmap(b); resultBitmap = b; originalBitmap = b; } BitmapDrawable invertBitmap = new BitmapDrawable(getResources(),Bitmap.createScaledBitmap(changeToInvert(originalBitmap),100,100,false)); filterInvert.setBackgroundDrawable(invertBitmap); BitmapDrawable grayBitmap = new BitmapDrawable(getResources(),Bitmap.createScaledBitmap(GrayFilter(originalBitmap),100,100,false)); filterGray.setBackgroundDrawable(grayBitmap); BitmapDrawable oldBitmap = new BitmapDrawable(getResources(),Bitmap.createScaledBitmap(changeToOld(originalBitmap),100,100,false)); filterOld.setBackgroundDrawable(oldBitmap); BitmapDrawable original = new BitmapDrawable(getResources(),Bitmap.createScaledBitmap(originalBitmap,100,100,false)); filterOriginal.setBackgroundDrawable(original); //<------------------------Button NEXTSTEP--------------------------> nextstep.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(PhotoFilters.this, PhotoUpload.class); ByteArrayOutputStream bs = new ByteArrayOutputStream(); resultBitmap.compress(Bitmap.CompressFormat.PNG, 50, bs); intent.putExtra("byteArray", bs.toByteArray()); startActivity(intent); } }); //<------------------------Button FILTER_INVERT--------------------------> filterInvert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { filterImage.setImageBitmap(changeToInvert(originalBitmap)); resultBitmap = changeToInvert(originalBitmap); } }); //<------------------------Button FILTER_GRAY--------------------------> filterGray.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { filterImage.setImageBitmap(GrayFilter(originalBitmap)); resultBitmap = GrayFilter(originalBitmap); } }); //<------------------------Button FILTER_OLD--------------------------> filterOld.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { filterImage.setImageBitmap(changeToOld(originalBitmap)); resultBitmap = changeToOld(originalBitmap); } }); //<------------------------Button FILTER_OLD--------------------------> filterOriginal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { filterImage.setImageBitmap(originalBitmap); resultBitmap = originalBitmap; } }); } //<------------------------Filter_1_INVERT(Method)--------------------------> public static Bitmap changeToInvert(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap returnBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); int colorArray[] = new int[width * height]; int r, g, b; bitmap.getPixels(colorArray, 0, width, 0, 0, width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { r = 255 - Color.red(colorArray[y * width + x]); g = 255 - Color.green(colorArray[y * width + x]); b = 255 - Color.blue(colorArray[y * width + x]); colorArray[y * width + x] = Color.rgb(r, g, b); returnBitmap.setPixel(x, y, colorArray[y * width + x]); } } return returnBitmap; } //<------------------------Filter_2_GRAY(Method)--------------------------> public static Bitmap GrayFilter(Bitmap bitmap) { int width, height; width = bitmap.getWidth(); height = bitmap.getHeight(); Bitmap grayBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(grayBitmap); Paint paint = new Paint(); paint.setAntiAlias(true); ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setSaturation(0); ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix); paint.setColorFilter(filter); canvas.drawBitmap(bitmap, 0, 0, paint); return grayBitmap; } //<------------------------Filter_3_OLD(Method)--------------------------> public static Bitmap changeToOld(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int pixColor = 0; int pixR = 0; int pixG = 0; int pixB = 0; int newR = 0; int newG = 0; int newB = 0; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i = 0; i < height; i++) { for (int k = 0; k < width; k++) { pixColor = pixels[width * i + k]; pixR = Color.red(pixColor); pixG = Color.green(pixColor); pixB = Color.blue(pixColor); newR = (int) (0.393 * pixR + 0.769 * pixG + 0.189 * pixB); newG = (int) (0.349 * pixR + 0.686 * pixG + 0.168 * pixB); newB = (int) (0.272 * pixR + 0.534 * pixG + 0.131 * pixB); int newColor = Color.argb(255, newR > 255 ? 255 : newR, newG > 255 ? 255 : newG, newB > 255 ? 255 : newB); pixels[width * i + k] = newColor; } } Bitmap returnBitmap = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888); return returnBitmap; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_photo_filters, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
/* * Copyright (c) 2010-2014 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of dyn4j nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j; import java.util.Iterator; import junit.framework.TestCase; import org.dyn4j.BinarySearchTree; import org.junit.Before; import org.junit.Test; /** * Test case for the {@link BinarySearchTree} class. * @author William Bittle * @version 2.2.0 * @since 2.2.0 */ public class BalancedBinarySearchTreeTest { /** The golden ratio for testing the height of a balanced binary tree */ private static final double GOLDEN_RATIO = (1.0 + Math.sqrt(5.0)) / 2.0; /** The binary tree */ private BinarySearchTree<Integer> tree; /** * Sets up the binary tree and populates with data. */ @Before public void setup() { tree = new BinarySearchTree<Integer>(true); tree.insert(10); tree.insert(3); tree.insert(-3); tree.insert(4); tree.insert(0); tree.insert(1); tree.insert(11); tree.insert(19); tree.insert(6); tree.insert(-1); tree.insert(2); tree.insert(9); tree.insert(-4); } /** * Returns the height limit of a balanced binary tree of the given size. * @param size the size of the tree * @return the height limit */ private static final double getHeightLimit(int size) { return Math.log((size + 2.0) - 1.0) / Math.log(GOLDEN_RATIO); } /** * Tests the insert methods. */ @Test public void insert() { // after setup the tree should be balanced double hl = getHeightLimit(tree.size()); TestCase.assertTrue(tree.getHeight() < hl); TestCase.assertFalse(tree.contains(5)); TestCase.assertTrue(tree.insert(5)); TestCase.assertTrue(tree.contains(5)); BinarySearchTree<Integer> t2 = new BinarySearchTree<Integer>(); t2.insert(14); t2.insert(8); t2.insert(16); t2.insert(15); TestCase.assertFalse(tree.contains(14)); TestCase.assertFalse(tree.contains(8)); TestCase.assertFalse(tree.contains(16)); TestCase.assertFalse(tree.contains(15)); tree.insertSubtree(t2.root); TestCase.assertTrue(tree.contains(14)); TestCase.assertTrue(tree.contains(8)); TestCase.assertTrue(tree.contains(16)); TestCase.assertTrue(tree.contains(15)); hl = getHeightLimit(tree.size()); TestCase.assertTrue(tree.getHeight() < hl); } /** * Tests the remove method with a valid value. */ @Test public void remove() { TestCase.assertNotNull(tree.remove(-3)); // make sure it was removed TestCase.assertFalse(tree.contains(-3)); // make sure the other values around that node are still there TestCase.assertTrue(tree.contains(-4)); TestCase.assertTrue(tree.contains(0)); TestCase.assertTrue(tree.contains(1)); TestCase.assertTrue(tree.contains(2)); TestCase.assertTrue(tree.contains(3)); // remove the minimum of the entire tree int size = tree.size(); tree.removeMinimum(); TestCase.assertFalse(tree.contains(-4)); TestCase.assertEquals(size - 1, tree.size()); BinarySearchTree<Integer>.Node node = tree.get(10); tree.removeMinimum(node); TestCase.assertFalse(tree.contains(4)); TestCase.assertEquals(size - 2, tree.size()); tree.removeMaximum(); TestCase.assertFalse(tree.contains(19)); TestCase.assertEquals(size - 3, tree.size()); node = tree.get(0); tree.removeMaximum(node); TestCase.assertFalse(tree.contains(2)); TestCase.assertEquals(size - 4, tree.size()); double hl = getHeightLimit(tree.size()); TestCase.assertTrue(tree.getHeight() < hl); tree.removeSubtree(0); TestCase.assertFalse(tree.contains(0)); TestCase.assertFalse(tree.contains(-1)); TestCase.assertFalse(tree.contains(1)); TestCase.assertFalse(tree.contains(2)); TestCase.assertEquals(tree.size(), 5); hl = getHeightLimit(tree.size()); TestCase.assertTrue(tree.getHeight() < hl); } /** * Tests the remove methods with non-existing values. */ @Test public void removeNotFound() { TestCase.assertFalse(tree.remove(7)); BinarySearchTree<Integer>.Node node = tree.new Node(-3); TestCase.assertFalse(tree.remove(node)); } /** * Tests the getDepth methods. */ @Test public void getDepth() { TestCase.assertEquals(4, tree.getHeight()); BinarySearchTree<Integer>.Node node = tree.get(-3); TestCase.assertEquals(2, tree.getHeight(node)); } /** * Tests the getMinimum methods. */ @Test public void getMinimum() { TestCase.assertEquals(-4, (int) tree.getMinimum()); BinarySearchTree<Integer>.Node node = tree.get(10); TestCase.assertEquals(4, (int) tree.getMinimum(node).comparable); node = tree.get(1); TestCase.assertEquals(1, (int) tree.getMinimum(node).comparable); } /** * Tests the getMaximum methods. */ @Test public void getMaximum() { TestCase.assertEquals(19, (int) tree.getMaximum()); BinarySearchTree<Integer>.Node node = tree.get(-3); TestCase.assertEquals(-1, (int) tree.getMaximum(node).comparable); node = tree.get(6); TestCase.assertEquals(9, (int) tree.getMaximum(node).comparable); } /** * Tests the isEmpty method. */ @Test public void isEmpty() { TestCase.assertFalse(tree.isEmpty()); BinarySearchTree<Integer> test = new BinarySearchTree<Integer>(); TestCase.assertTrue(test.isEmpty()); } /** * Tests the clear method. */ @Test public void clear() { TestCase.assertFalse(tree.isEmpty()); TestCase.assertEquals(13, tree.size()); tree.clear(); TestCase.assertTrue(tree.isEmpty()); TestCase.assertEquals(0, tree.size()); TestCase.assertEquals(0, tree.getHeight()); TestCase.assertEquals(null, tree.getRoot()); } /** * Tests the contains method. */ @Test public void contains() { TestCase.assertTrue(tree.contains(9)); TestCase.assertFalse(tree.contains(14)); BinarySearchTree<Integer>.Node node = tree.get(-3); TestCase.assertTrue(tree.contains(node)); node = tree.new Node(-3); TestCase.assertFalse(tree.contains(node)); } /** * Tests the get method. */ @Test public void get() { TestCase.assertNotNull(tree.get(-3)); TestCase.assertNull(tree.get(45)); } /** * Tests the size methods. */ @Test public void size() { TestCase.assertEquals(13, tree.size()); BinarySearchTree<Integer>.Node node = tree.get(-3); TestCase.assertEquals(3, tree.size(node)); } /** * Tests the iterators. */ @Test public void iterator() { // test in order traversal Iterator<Integer> it = tree.inOrderIterator(); int last = Integer.MIN_VALUE; while (it.hasNext()) { int i = it.next(); if (i < last) { TestCase.fail(); } last = i; } // test reverse order traversal it = tree.reverseOrderIterator(); last = Integer.MAX_VALUE; while (it.hasNext()) { int i = it.next(); if (i > last) { TestCase.fail(); } last = i; } } }
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.sop4j.base.google.common.primitives; import static com.sop4j.base.google.common.base.Preconditions.checkArgument; import static com.sop4j.base.google.common.base.Preconditions.checkNotNull; import com.sop4j.base.google.common.annotations.Beta; import com.sop4j.base.google.common.annotations.GwtCompatible; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; /** * Static utility methods pertaining to {@code long} primitives that interpret values as * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value * {@code 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as * well as signed versions of methods for which signedness is an issue. * * <p>In addition, this class provides several static methods for converting a {@code long} to a * {@code String} and a {@code String} to a {@code long} that treat the {@code long} as an unsigned * number. * * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned * {@code long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper * class be used, at a small efficiency penalty, to enforce the distinction in the type system. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @author Brian Milch * @author Colin Evans * @since 10.0 */ @Beta @GwtCompatible public final class UnsignedLongs { private UnsignedLongs() {} public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 /** * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on * longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} * as signed longs. */ private static long flip(long a) { return a ^ Long.MIN_VALUE; } /** * Compares the two specified {@code long} values, treating them as unsigned values between * {@code 0} and {@code 2^64 - 1} inclusive. * * @param a the first unsigned {@code long} to compare * @param b the second unsigned {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); } /** * Returns the least value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is less than or equal to every other value in * the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } /** * Returns the greatest value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } /** * Returns a string containing the supplied unsigned {@code long} values separated by * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting * string (but not at the start or end) * @param array an array of unsigned {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(toString(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two arrays of unsigned {@code long} values * lexicographically. That is, it compares, using {@link #compare(long, long)}), the first pair of * values that follow any common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with * {@link Arrays#equals(long[], long[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order * article at Wikipedia</a> */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedLongs.compare(left[i], right[i]); } } return left.length - right.length; } } /** * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static long divide(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return 0; // dividend < divisor } else { return 1; // dividend >= divisor } } // Optimization - use signed division if dividend < 2^63 if (dividend >= 0) { return dividend / divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); } /** * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 * @since 11.0 */ public static long remainder(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return dividend; // dividend < divisor } else { return dividend - divisor; // dividend >= divisor } } // Optimization - use signed modulus if dividend < 2^63 if (dividend >= 0) { return dividend % divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } /** * Returns the unsigned {@code long} value represented by the given decimal string. * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value * @throws NullPointerException if {@code s} is null * (in contrast to {@link Long#parseLong(String)}) */ public static long parseUnsignedLong(String s) { return parseUnsignedLong(s, 10); } /** * Returns the unsigned {@code long} value represented by the given string. * * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix: * * <ul> * <li>{@code 0x}<i>HexDigits</i> * <li>{@code 0X}<i>HexDigits</i> * <li>{@code #}<i>HexDigits</i> * <li>{@code 0}<i>OctalDigits</i> * </ul> * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value * @since 13.0 */ public static long decode(String stringValue) { ParseRequest request = ParseRequest.fromString(stringValue); try { return parseUnsignedLong(request.rawValue, request.radix); } catch (NumberFormatException e) { NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); decodeException.initCause(e); throw decodeException; } } /** * Returns the unsigned {@code long} value represented by a string with the given radix. * * @param s the string containing the unsigned {@code long} representation to be parsed. * @param radix the radix to use while parsing {@code s} * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. * @throws NullPointerException if {@code s} is null * (in contrast to {@link Long#parseLong(String)}) */ public static long parseUnsignedLong(String s, int radix) { checkNotNull(s); if (s.length() == 0) { throw new NumberFormatException("empty string"); } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException("illegal radix: " + radix); } int max_safe_pos = maxSafeDigits[radix] - 1; long value = 0; for (int pos = 0; pos < s.length(); pos++) { int digit = Character.digit(s.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(s); } if (pos > max_safe_pos && overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + s); } value = (value * radix) + digit; } return value; } /** * Returns true if (current * radix) + digit is a number too large to be represented by an * unsigned long. This is useful for detecting overflow while parsing a string representation of * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give * undefined results or an ArrayIndexOutOfBoundsException. */ private static boolean overflowInParse(long current, int digit, int radix) { if (current >= 0) { if (current < maxValueDivs[radix]) { return false; } if (current > maxValueDivs[radix]) { return true; } // current == maxValueDivs[radix] return (digit > maxValueMods[radix]); } // current < 0: high bit is set return true; } /** * Returns a string representation of x, where x is treated as unsigned. */ public static String toString(long x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated * as unsigned. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static String toString(long x, int radix) { checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); if (x == 0) { // Simply return "0" return "0"; } else { char[] buf = new char[64]; int i = buf.length; if (x < 0) { // Separate off the last digit using unsigned division. That will leave // a number that is nonnegative as a signed integer. long quotient = divide(x, radix); long rem = x - quotient * radix; buf[--i] = Character.forDigit((int) rem, radix); x = quotient; } // Simple modulo/division approach while (x > 0) { buf[--i] = Character.forDigit((int) (x % radix), radix); x /= radix; } // Generate string return new String(buf, i, buf.length - i); } } // calculated as 0xffffffffffffffff / radix private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; static { BigInteger overflow = new BigInteger("10000000000000000", 16); for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { maxValueDivs[i] = divide(MAX_VALUE, i); maxValueMods[i] = (int) remainder(MAX_VALUE, i); maxSafeDigits[i] = overflow.toString(i).length() - 1; } } }
/* * PhoneContact.java * * Created on April 26, 2001, 9:08 PM */ import CiaoJava.*; /** * * @author jcorreas * @version */ public class PhoneSearch extends javax.swing.JDialog { /** Creates new form PhoneSearch */ public PhoneSearch(java.awt.Frame parent,boolean modal) { super (parent, modal); initComponents (); //pack (); } /** 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 FormEditor. */ private void initComponents() {//GEN-BEGIN:initComponents jPanel6 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); txtName = new javax.swing.JTextField(); txtPhone = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jPanel9 = new javax.swing.JPanel(); txtEmail = new javax.swing.JTextField(); txtAddress = new javax.swing.JTextField(); jPanel10 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jPanel11 = new javax.swing.JPanel(); txtPosition = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); rbExactMatch = new javax.swing.JRadioButton(); rbICase = new javax.swing.JRadioButton(); rbWCAllowed = new javax.swing.JRadioButton(); jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); btnOk = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); getContentPane().setLayout(new java.awt.GridLayout(4, 2)); setTitle("Search Dialog"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { closeDialog(evt); } } ); jPanel6.setLayout(new java.awt.GridLayout(2, 1)); jLabel1.setText("Name"); jPanel6.add(jLabel1); jLabel2.setText("Telephone"); jPanel6.add(jLabel2); getContentPane().add(jPanel6); jPanel7.setLayout(new java.awt.GridLayout(2, 1)); jPanel7.add(txtName); jPanel7.add(txtPhone); getContentPane().add(jPanel7); jPanel8.setLayout(new java.awt.GridLayout(2, 1)); jLabel3.setText("E-mail"); jPanel8.add(jLabel3); jLabel4.setText("Address"); jPanel8.add(jLabel4); getContentPane().add(jPanel8); jPanel9.setLayout(new java.awt.GridLayout(2, 1)); jPanel9.add(txtEmail); jPanel9.add(txtAddress); getContentPane().add(jPanel9); jPanel10.setLayout(new java.awt.GridLayout(2, 1)); jLabel5.setText("Position"); jPanel10.add(jLabel5); getContentPane().add(jPanel10); jPanel11.setLayout(new java.awt.GridLayout(2, 1)); jPanel11.add(txtPosition); getContentPane().add(jPanel11); jPanel2.setLayout(new java.awt.GridLayout(3, 1)); jPanel2.setBorder(new javax.swing.border.EtchedBorder()); rbExactMatch.setLabel("Exact match"); rbExactMatch.setSelected(true); jPanel2.add(rbExactMatch); rbICase.setLabel("Ignore case"); jPanel2.add(rbICase); rbWCAllowed.setLabel("Wildcards allowed"); jPanel2.add(rbWCAllowed); getContentPane().add(jPanel2); jPanel1.setLayout(new java.awt.GridLayout(2, 2)); jPanel1.add(jPanel3); jPanel1.add(jPanel4); btnOk.setText("OK"); btnOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOkActionPerformed(evt); } } ); jPanel1.add(btnOk); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } } ); jPanel1.add(btnCancel); getContentPane().add(jPanel1); pack(); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); java.awt.Dimension dialogSize = getSize(); setSize(new java.awt.Dimension(400, 200)); setLocation((screenSize.width-400)/2,(screenSize.height-200)/2); }//GEN-END:initComponents private void rbExactMatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbExactMatchActionPerformed // Add your handling code here: }//GEN-LAST:event_rbExactMatchActionPerformed /* ----------------------------------------------------- * Begin of Ciao specific code. * -----------------------------------------------------*/ javax.swing.ButtonGroup bg = new javax.swing.ButtonGroup(); public void show() { bg.add(rbExactMatch); bg.add(rbWCAllowed); bg.add(rbICase); super.show(); } private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed // Begin Ciao specific code. // Gets the form data and invokes PhoneList method to do // the actual search. String filter[] = new String[5]; filter[0] = txtName.getText(); filter[1] = txtPhone.getText(); filter[2] = txtEmail.getText(); filter[3] = txtAddress.getText(); filter[4] = txtPosition.getText(); int searchMode; if (rbExactMatch.isSelected()) searchMode = PhoneList.NORMAL; else if (rbWCAllowed.isSelected()) searchMode = PhoneList.REG_EXP; else if (rbICase.isSelected()) searchMode = PhoneList.CASE_INS; else searchMode = PhoneList.NORMAL; ((PhoneList)getOwner()).refreshList(filter, searchMode); setVisible(false); dispose(); // End Ciao specific code. }//GEN-LAST:event_btnOkActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed // Begin Ciao specific code. // Closes this form. setVisible(false); dispose(); // End Ciao specific code. }//GEN-LAST:event_btnCancelActionPerformed /** Closes the dialog */ private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog setVisible (false); dispose (); }//GEN-LAST:event_closeDialog // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel6; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel7; private javax.swing.JTextField txtName; private javax.swing.JTextField txtPhone; private javax.swing.JPanel jPanel8; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel9; private javax.swing.JTextField txtEmail; private javax.swing.JTextField txtAddress; private javax.swing.JPanel jPanel10; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel11; private javax.swing.JTextField txtPosition; private javax.swing.JPanel jPanel2; private javax.swing.JRadioButton rbExactMatch; private javax.swing.JRadioButton rbICase; private javax.swing.JRadioButton rbWCAllowed; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JButton btnOk; private javax.swing.JButton btnCancel; // End of variables declaration//GEN-END:variables }
package main; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.Scanner; public class PrintVitalSource { private static Robot robot = null; // This is the class to auto-type/click. MUST be called first for program to work private static Scanner input = new Scanner(System.in); // Scanner to get user input from keyboard private static int printAmount; private static int numberOfPages; private final static int DELAY_TIME_MILLISECOND = 500; // Delay the task by milliseconds between each task /** Constructor runs needed methods to use class */ // Helpful tip, always have a no-arg constructor otherwise any sub-class will complain public PrintVitalSource() { initializeRobot(); // First thing to be ran, otherwise Robot can't be used printAmount = 1; } // Program Methods ***************************************************************************************** /** Verify user has read README */ private static void confirmUserReadREADME() { boolean userVerified = false; // To end loop // To confirm if user read the README while (!userVerified) { System.out.println("Must read README for instructions on how to run program. Very Crucial"); System.out.println("Did you read the README? Y (Yes) or N (No)"); if (input.next().equalsIgnoreCase("Y")) { userVerified = true; } } } /** Ask the user how many pages the book has */ private static void getTotalBookPages() { boolean userVerified = false; // To end loop // Get user input on amount of pages the book has and confirm if user is sure while (!userVerified) { // Get total book pages System.out.println("How many pages are there?"); numberOfPages = input.nextInt(); // Ask user if it's correct otherwise re-ask for the total book pages System.out.println("Are you sure? Y or N"); if (input.next().equalsIgnoreCase("Y")) { userVerified = true; // End loop because book pages is correct } } } /** Runs program */ public void run() { // Confirm user has read README confirmUserReadREADME(); // Ask the user how many pages the book has getTotalBookPages(); // Select Vital Source book selectVitalSource(); robot.delay(DELAY_TIME_MILLISECOND); // Delays any task in milliseconds // Each increment prints 10 pages, therefore increase i by 10 per loop for (int i = 0; i < numberOfPages; i += 10) { // Scroll controlment if (i == 0) { // if i == 0 then don't scroll because the first 10 pages need to be printed // Do nothing } else { // Print ten pages and save them and loop until end of book mouseScroll(10); // Scroll down ten pages } keyboardCtrlP(); // Press Control + P; shortcut for print robot.delay(DELAY_TIME_MILLISECOND); // On Print Preview GUI mouseMove(917, 587); // Move to "Continue" mouseClick(1); // Click "Continue" robot.delay(DELAY_TIME_MILLISECOND); // On Print GUI mouseMove(890, 482); // Move to "OK" mouseClick(1); // Click "OK" robot.delay(DELAY_TIME_MILLISECOND); // Save file saveFileAs(); robot.delay(15000); // Saving files take at least 11 seconds + 4 seconds of leeway // Show the user what page print you're on System.out.println("Close the CMD or press \"Control + C\" to STOP program"); if (i + 10 > numberOfPages) { System.out.println("Print " + numberOfPages + "of " + numberOfPages); System.out.println("DONE"); } System.out.println("Print " + (i + 10) + "of " + numberOfPages); } } /** Initialize Robot variable to Robot Class */ private static void initializeRobot() { // AWTException will only be thrown by Robot Class's Constructor and therefore only need to be initialize once try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); System.out.println("Problem with constructing Robot Class in VBKToXPSVersion4"); } } /** Automatically creates a name and saves a file */ private static void saveFileAs() { createSaveName(); // Create a save file with the printAmount as file name printAmount++; // Increase the print amount by one keyboardEnter(); // Press keyboardEnter to save file } /** * To select VitalSource program. Must have VitalSource book pre-loaded and * must be the first icon in Windows's 7 taskbar */ private static void selectVitalSource() { // Move mouse to first taskbar icon and click it mouseMove(90, 882); mouseClick(1); // Move mouse on Vital Source program to be able to be scrolled mouseMove(811, 480); } // Keyboard Task *************************************************************************************************** /** Type Enter */ private static void keyboardEnter() { // Click enter robot.keyPress(KeyEvent.VK_ENTER); robot.keyPress(KeyEvent.VK_ENTER); } /** Types Control + P to activate print shortcut */ private static void keyboardCtrlP() { // Auto type Ctrl + P for shortcut of Print robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_P); robot.keyRelease(KeyEvent.VK_CONTROL); robot.keyRelease(KeyEvent.VK_P); } /** Types the current print attempt as the file name */ private static void createSaveName() { String printAmountString = String.valueOf(printAmount); // To be able to find the print amount // Save a file named with the amount of prints for (int i = 0; i < printAmountString.length(); i++) { // Turn an int in a String to a char to be able to type it automatically switch (printAmountString.charAt(i)) { // Type 0 on keyboard and the same for the other cases respectively case '0': { robot.keyPress(KeyEvent.VK_0); robot.keyRelease(KeyEvent.VK_0); } break; case '1': { robot.keyPress(KeyEvent.VK_1); robot.keyRelease(KeyEvent.VK_1); } break; case '2': { robot.keyPress(KeyEvent.VK_2); robot.keyRelease(KeyEvent.VK_2); } break; case '3': { robot.keyPress(KeyEvent.VK_3); robot.keyRelease(KeyEvent.VK_3); } break; case '4': { robot.keyPress(KeyEvent.VK_4); robot.keyRelease(KeyEvent.VK_4); } break; case '5': { robot.keyPress(KeyEvent.VK_5); robot.keyRelease(KeyEvent.VK_5); } break; case '6': { robot.keyPress(KeyEvent.VK_6); robot.keyRelease(KeyEvent.VK_6); } break; case '7': { robot.keyPress(KeyEvent.VK_7); robot.keyRelease(KeyEvent.VK_7); } break; case '8': { robot.keyPress(KeyEvent.VK_8); robot.keyRelease(KeyEvent.VK_8); } break; case '9': { robot.keyPress(KeyEvent.VK_9); robot.keyRelease(KeyEvent.VK_9); } break; default: { System.out.println("Not Valid Input Found IN createSaveName()"); } } } } // Mouse Task ****************************************************************************************************** /** * Move mouse to a location on the screen from the provided coordinates * * @param xCoordinate * Vertical coordinates on the monitor * @param yCoordinate * Horizontal coordinates on the monitor */ private static void mouseMove(int xCoordinate, int yCoordinate) { robot.mouseMove(xCoordinate, yCoordinate); } /** Automatically left click a mouse X amount */ private static void mouseClick(int amount) { int click = InputEvent.BUTTON1_DOWN_MASK; // int code for left mouse button (mouse button1) // Code to automatically left click a mouse for (int i = 0; i < amount; i++) { robot.mousePress(click); robot.mouseRelease(click); } } /** * Used to scroll mouse button * * @param amountOfScrolls * Negative number scrolls up, positive number scrolls down */ private static void mouseScroll(int amountOfScrolls) { // scroll x amount of times for (int i = 0; i < amountOfScrolls; i++) { robot.delay(200); robot.mouseWheel(1); // Must be one because VitalSource doesn't register scrolls very well } } }
package info.freelibrary.edtf; import static org.junit.Assert.*; import org.junit.Test; import org.junit.BeforeClass; public class EDTFParserTest { private static EDTFParser myParser; @BeforeClass public static void runBeforeClass() { myParser = new EDTFParser(); } @Test public void level0YearTest() { try { // Standard ISO 8601 four-digit year myParser.parse("1991"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Spec assumes astronomical numbering, which includes year zero myParser.parse("0000"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Year MUST have four digits so below should throw exception myParser.parse("400"); fail("Parser allowed less than four digit year"); } catch (SyntaxException details) {} try { // Negative years are allowed myParser.parse("-1000"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0YearMonthTest() { try { // Standard ISO 8601 four-digit year and two digit month myParser.parse("1990-12"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Standard ISO 8601 four-digit year and two digit month myParser.parse("1992/12"); fail("Year-month dates must use a hyphen as a delimiter"); } catch (SyntaxException details) {} try { // Negative year-month dates are allowed myParser.parse("-1993-12"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Year MUST have four digits so below should throw exception myParser.parse("400-12"); fail("Parser allowed less than four digit year"); } catch (SyntaxException details) {} try { // Month MUST have two digits so below should throw exception myParser.parse("1994-1"); fail("Parser allowed less than two digit month"); } catch (SyntaxException details) {} } @Test public void level0YearMonthDayTest() { try { // Standard ISO 8601 4 digit year, 2 digit month, 2 digit day myParser.parse("1992-12-12"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Negative year-month-day dates are allowed myParser.parse("-1993-12-01"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Day MUST have two digits so below should throw exception myParser.parse("1984-01-1"); fail("Parser allowed less than two digit day"); } catch (SyntaxException details) {} try { // Month MUST have two digits so below should throw exception myParser.parse("1994-1-01"); fail("Parser allowed less than two digit month"); } catch (SyntaxException details) {} try { // Day month combination must be valid myParser.parse("1986-02-31"); fail("Parser allowed invalid day-month combination: 1986-02-31"); } catch (SyntaxException details) {} } @Test public void level0HourMinuteSecondTest() { try { // Standard ISO 8601 4 digit year, 2 digit month, 2 digit day myParser.parse("2001-02-03T09:30:01"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Negative ISO 8601 4 digit year, 2 digit month, 2 digit day myParser.parse("-2007-02-03T09:30:01"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Year, month, day delimiters should be dashes, not slashes myParser.parse("1971/02/03T09:30:01"); fail("Failed to disallow slashes for year, month, day delimiters"); } catch (SyntaxException details) {} try { // 'T' should be used as the date/time delimiter myParser.parse("1973-02-03 09:30:01"); fail("Failed to require 'T' as date/time delimiter"); } catch (SyntaxException details) {} try { // ':' should be used as time unit delimiter myParser.parse("1972-02-03T09-30-01"); fail("Failed to require ':' as time unit delimiter"); } catch (SyntaxException details) {} try { // Standard ISO 8601 in Zulu time zone myParser.parse("1998-01-03T09:30:01Z"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Testing Zulu time zone but with other character myParser.parse("1962-02-03T09-30-01T"); fail("Failed to require 'Z' as Zulu time zone indicator"); } catch (SyntaxException details) {} try { // Standard ISO 8601 with 24:00:00 myParser.parse("1893-01-03T24:00:00"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("1883-01-03T24:00:00+01:59"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("1883-01-03T24:00:00+14:00"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("1883-01-03T24:00:00-14:00"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("1883-01-03T24:00:00-00:45"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0IntervalTestYMDYM() { try { myParser.parse("2004-02-01/2005-02"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0IntervalTestYMDYMD() { try { myParser.parse("2004-02-01/2005-02-08"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0IntervalTestYMYM() { try { myParser.parse("2004-06/2006-08"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0IntervalTestYY() { try { myParser.parse("1964/2008"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0IntervalTestYMDY() { try { myParser.parse("2004-02-01/2005"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level0IntervalTestYYM() { try { myParser.parse("2005/2006-02"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level1UncertainOrApproxDateTest() { try { myParser.parse("2001?"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2001~"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2001?~"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2002-12?"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2002-12~"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2002-12?~"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2003-12-01?"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2003-12-01~"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2001-12-01?~"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1UnspecifiedTest() { try { myParser.parse("199u"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("19uu"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("1999-uu"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("1999-01-uu"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("1999-uu-uu"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1LongYearSimpleTest() { try { myParser.parse("y170000002"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("y-170000002"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1SeasonTest() { try { myParser.parse("2001-21"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2003-22"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2000-23"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2010-24"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("2010-25"); fail("Failed to catch an invalid season value"); } catch (SyntaxException details) {} } @Test public void level1IntervalTestUnknownY() { try { myParser.parse("unknown/2006"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYMDUnknown() { try { myParser.parse("2004-06-01/unknown"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYMDOpen() { try { myParser.parse("2004-01-01/open"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYearuaYM() { try { myParser.parse("1984~/2004-06"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYYMua() { try { myParser.parse("1984/2004-06~"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYuaYua() { try { myParser.parse("1984~/2004~"); } catch (SyntaxException details) { fail(details.getMessage()); } try { myParser.parse("1984?/2004?~"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYMuaYMua() { try { myParser.parse("1984-06?/2004-08?"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYMDuaYMDua() { try { myParser.parse("1984-06-02?/2004-08-08~"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestYMDuaUnknown() { try { myParser.parse("1984-06-02?/unknown"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level1IntervalTestUnknownYM() { try { myParser.parse("unknown/2013-21"); } catch (SyntaxException details) { fail(details.getMessage()); } } @Test public void level2PartialTestMDKnownYua() { try { // Uncertain year; month, day known myParser.parse("2004?-06-11"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestDKnownYMua() { try { // Year and month are approximate; day known myParser.parse("2004-06~-11"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Uncertain month, year and day known myParser.parse("2004-(06)?-11"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestYMKnownDua() { try { // Day is approximate; year, month known myParser.parse("2004-06-(11)~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestYKnownMua() { try { // Year known, month within year is approximate and uncertain myParser.parse("2004-(06)?~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestYKnownMDua() { try { // Year known, month and day uncertain myParser.parse("2004-(06-11)?"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Year known, month and day approximate myParser.parse("(2011)-06-04~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestMKnownYDua() { try { // Year uncertain, month known, day approximate myParser.parse("2004?-06-(11)~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestYMUa() { try { // Year uncertain and month is both uncertain and approximate myParser.parse("(2004-(06)~)?"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Year uncertain and month is both uncertain and approximate myParser.parse("2004?-(06)?~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestYMDua() { try { // Year uncertain, month and day approximate myParser.parse("(2004)?-06-04~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialTestSeason() { try { // Approximate season (around Autumn 2011) myParser.parse("2011-23~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2PartialUnspecifiedTest() { try { myParser.parse("156u-12-25"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("15uu-12-25"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("15uu-12-uu"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("1560-uu-25"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2LongYearScientificTest() { try { myParser.parse("y17e7"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("y-17e7"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("y17101e4p3"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2SeasonQualifiedTest() { try { myParser.parse("2001-21^southernHemisphere"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("2001-21^Southern Hemisphere"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2MaskedPrecisionTest() { try { myParser.parse("196x"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("19xx"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2OneOfSetTest() { try { // Try without spaces after the commas myParser.parse("[1667,1668,1670..1672]"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { // Try the same thing with a space after a comma myParser.parse("[1667,1668, 1670..1672]"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("[..1760-12-03]"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("[1760-12..]"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("[1760-01, 1760-02, 1760-12..]"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("[1667, 1760-12]"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2MultipleDatesTest() { try { myParser.parse("{1667,1668, 1670..1672}"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("{1960, 1961-12}"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } @Test public void level2ExtendedIntervalTest() { try { myParser.parse("2004-06-(01)~/2004-06-(20)~"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } try { myParser.parse("2004-06-uu/2004-07-03"); } catch (SyntaxException details) { details.printStackTrace(System.err); fail(details.getMessage()); } } }
package com.grapecity.debugrank.javalib.entities; /** * Created by chrisr on 1/27/2016. */ public class Result { private String result; private String[] stdout; private String[] diff_status; private String hash; private String error_code; private String[] signal; private String[] stderr; private String codechecker_hash; private String custom_score; private String[] memory; private String[] message; private String[] time; private String[] censored_stderr; private String created_at; private String custom_status; private String server; private String callback_url; private String compilemessage; private String censored_compile_message; private String response_s3_path; public String getResult () { return result; } public void setResult (String result) { this.result = result; } public String[] getStdout () { return stdout; } public void setStdout (String[] stdout) { this.stdout = stdout; } public String[] getDiff_status () { return diff_status; } public void setDiff_status (String[] diff_status) { this.diff_status = diff_status; } public String getHash () { return hash; } public void setHash (String hash) { this.hash = hash; } public String getError_code () { return error_code; } public void setError_code (String error_code) { this.error_code = error_code; } public String[] getSignal () { return signal; } public void setSignal (String[] signal) { this.signal = signal; } public String[] getStderr () { return stderr; } public void setStderr (String[] stderr) { this.stderr = stderr; } public String getCodechecker_hash () { return codechecker_hash; } public void setCodechecker_hash (String codechecker_hash) { this.codechecker_hash = codechecker_hash; } public String getCustom_score () { return custom_score; } public void setCustom_score (String custom_score) { this.custom_score = custom_score; } public String[] getMemory () { return memory; } public void setMemory (String[] memory) { this.memory = memory; } public String[] getMessage () { return message; } public void setMessage (String[] message) { this.message = message; } public String[] getTime () { return time; } public void setTime (String[] time) { this.time = time; } public String[] getCensored_stderr () { return censored_stderr; } public void setCensored_stderr (String[] censored_stderr) { this.censored_stderr = censored_stderr; } public String getCreated_at () { return created_at; } public void setCreated_at (String created_at) { this.created_at = created_at; } public String getCustom_status () { return custom_status; } public void setCustom_status (String custom_status) { this.custom_status = custom_status; } public String getServer () { return server; } public void setServer (String server) { this.server = server; } public String getCallback_url () { return callback_url; } public void setCallback_url (String callback_url) { this.callback_url = callback_url; } public String getCompilemessage () { return compilemessage; } public void setCompilemessage (String compilemessage) { this.compilemessage = compilemessage; } public String getCensored_compile_message () { return censored_compile_message; } public void setCensored_compile_message (String censored_compile_message) { this.censored_compile_message = censored_compile_message; } public String getResponse_s3_path () { return response_s3_path; } public void setResponse_s3_path (String response_s3_path) { this.response_s3_path = response_s3_path; } }
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.profiler.modifier.connector.asynchttpclient.interceptor; import java.io.InputStream; import java.util.*; import com.navercorp.pinpoint.bootstrap.config.DumpType; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.bootstrap.context.Header; import com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder; import com.navercorp.pinpoint.bootstrap.context.Trace; import com.navercorp.pinpoint.bootstrap.context.TraceContext; import com.navercorp.pinpoint.bootstrap.context.TraceId; import com.navercorp.pinpoint.bootstrap.interceptor.ByteCodeMethodDescriptorSupport; import com.navercorp.pinpoint.bootstrap.interceptor.MethodDescriptor; import com.navercorp.pinpoint.bootstrap.interceptor.SimpleAroundInterceptor; import com.navercorp.pinpoint.bootstrap.interceptor.TargetClassLoader; import com.navercorp.pinpoint.bootstrap.interceptor.TraceContextSupport; import com.navercorp.pinpoint.bootstrap.logging.PLogger; import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory; import com.navercorp.pinpoint.bootstrap.sampler.SamplingFlagUtils; import com.navercorp.pinpoint.bootstrap.util.InterceptorUtils; import com.navercorp.pinpoint.bootstrap.util.SimpleSampler; import com.navercorp.pinpoint.bootstrap.util.SimpleSamplerFactory; import com.navercorp.pinpoint.bootstrap.util.StringUtils; import com.navercorp.pinpoint.common.trace.AnnotationKey; import com.navercorp.pinpoint.common.trace.ServiceType; import com.ning.http.client.FluentCaseInsensitiveStringsMap; import com.ning.http.client.FluentStringsMap; import com.ning.http.client.Part; import com.ning.http.client.Request.EntityWriter; import com.ning.http.client.cookie.Cookie; /** * intercept com.ning.http.client.AsyncHttpClient.executeRequest(Request, * AsyncHandler<T>) * * @author netspider * */ public class ExecuteRequestInterceptor implements SimpleAroundInterceptor, ByteCodeMethodDescriptorSupport, TraceContextSupport, TargetClassLoader { protected final PLogger logger = PLoggerFactory.getLogger(ExecuteRequestInterceptor.class); protected final boolean isDebug = logger.isDebugEnabled(); protected TraceContext traceContext; protected MethodDescriptor descriptor; protected boolean dumpCookie; protected DumpType cookieDumpType; protected SimpleSampler cookieSampler; protected int cookieDumpSize; protected boolean dumpEntity; protected DumpType entityDumpType; protected SimpleSampler entitySampler; protected int entityDumpSize; protected boolean dumpParam; protected DumpType paramDumpType; protected SimpleSampler paramSampler; protected int paramDumpSize; @Override public void before(Object target, Object[] args) { if (isDebug) { logger.beforeInterceptor(target, args); } final Trace trace = traceContext.currentRawTraceObject(); if (trace == null) { return; } if (args.length == 0 || !(args[0] instanceof com.ning.http.client.Request)) { return; } final com.ning.http.client.Request httpRequest = (com.ning.http.client.Request) args[0]; final boolean sampling = trace.canSampled(); if (!sampling) { if (isDebug) { logger.debug("set Sampling flag=false"); } if (httpRequest != null) { final FluentCaseInsensitiveStringsMap httpRequestHeaders = httpRequest.getHeaders(); httpRequestHeaders.add(Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE); } return; } trace.traceBlockBegin(); SpanEventRecorder recorder = trace.currentSpanEventRecorder(); TraceId nextId = trace.getTraceId().getNextTraceId(); recorder.recordNextSpanId(nextId.getSpanId()); recorder.recordServiceType(ServiceType.HTTP_CLIENT); if (httpRequest != null) { final FluentCaseInsensitiveStringsMap httpRequestHeaders = httpRequest.getHeaders(); putHeader(httpRequestHeaders, Header.HTTP_TRACE_ID.toString(), nextId.getTransactionId()); putHeader(httpRequestHeaders, Header.HTTP_SPAN_ID.toString(), String.valueOf(nextId.getSpanId())); putHeader(httpRequestHeaders, Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(nextId.getParentSpanId())); putHeader(httpRequestHeaders, Header.HTTP_FLAGS.toString(), String.valueOf(nextId.getFlags())); putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_NAME.toString(), traceContext.getApplicationName()); putHeader(httpRequestHeaders, Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(traceContext.getServerTypeCode())); final String host = httpRequest.getURI().getHost(); if(host != null) { putHeader(httpRequestHeaders, Header.HTTP_HOST.toString(), host); } } } private void putHeader(FluentCaseInsensitiveStringsMap httpRequestHeaders, String key, String value) { final List<String> valueList = new ArrayList<String>(); valueList.add(value); httpRequestHeaders.put(key, valueList); } @Override public void after(Object target, Object[] args, Object result, Throwable throwable) { if (isDebug) { // Do not log result logger.afterInterceptor(target, args); } final Trace trace = traceContext.currentTraceObject(); if (trace == null) { return; } if (args.length == 0 || !(args[0] instanceof com.ning.http.client.Request)) { return; } try { SpanEventRecorder recorder = trace.currentSpanEventRecorder(); final com.ning.http.client.Request httpRequest = (com.ning.http.client.Request) args[0]; if (httpRequest != null) { // Accessing httpRequest here not before() because it can cause side effect. recorder.recordAttribute(AnnotationKey.HTTP_URL, httpRequest.getUrl()); String endpoint = getEndpoint(httpRequest.getURI().getHost(), httpRequest.getURI().getPort()); recorder.recordDestinationId(endpoint); recordHttpRequest(recorder, httpRequest, throwable); } recorder.recordApi(descriptor); recorder.recordException(throwable); } finally { trace.traceBlockEnd(); } } private String getEndpoint(String host, int port) { if (host == null) { return "UnknownHttpClient"; } if (port < 0) { return host; } final StringBuilder sb = new StringBuilder(host.length() + 8); sb.append(host); sb.append(':'); sb.append(port); return sb.toString(); } private void recordHttpRequest(SpanEventRecorder recorder, com.ning.http.client.Request httpRequest, Throwable throwable) { final boolean isException = InterceptorUtils.isThrowable(throwable); if (dumpCookie) { if (DumpType.ALWAYS == cookieDumpType) { recordCookie(httpRequest, recorder); } else if (DumpType.EXCEPTION == cookieDumpType && isException) { recordCookie(httpRequest, recorder); } } if (dumpEntity) { if (DumpType.ALWAYS == entityDumpType) { recordEntity(httpRequest, recorder); } else if (DumpType.EXCEPTION == entityDumpType && isException) { recordEntity(httpRequest, recorder); } } if (dumpParam) { if (DumpType.ALWAYS == paramDumpType) { recordParam(httpRequest, recorder); } else if (DumpType.EXCEPTION == paramDumpType && isException) { recordParam(httpRequest, recorder); } } } protected void recordCookie(com.ning.http.client.Request httpRequest, SpanEventRecorder recorder) { if (cookieSampler.isSampling()) { Collection<Cookie> cookies = httpRequest.getCookies(); if (cookies.isEmpty()) { return; } StringBuilder sb = new StringBuilder(cookieDumpSize * 2); Iterator<Cookie> iterator = cookies.iterator(); while (iterator.hasNext()) { Cookie cookie = iterator.next(); sb.append(cookie.getName()).append("=").append(cookie.getValue()); if (iterator.hasNext()) { sb.append(","); } } recorder.recordAttribute(AnnotationKey.HTTP_COOKIE, StringUtils.drop(sb.toString(), cookieDumpSize)); } } protected void recordEntity(final com.ning.http.client.Request httpRequest, final SpanEventRecorder recorder) { if (entitySampler.isSampling()) { recordNonMultipartData(httpRequest, recorder); recordMultipartData(httpRequest, recorder); } } /** * <pre> * Body could be String, byte array, Stream or EntityWriter. * We collect String data only. * </pre> * * @param httpRequest * @param recorder */ protected void recordNonMultipartData(final com.ning.http.client.Request httpRequest, final SpanEventRecorder recorder) { final String stringData = httpRequest.getStringData(); if (stringData != null) { recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, StringUtils.drop(stringData, entityDumpSize)); return; } final byte[] byteData = httpRequest.getByteData(); if (byteData != null) { recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "BYTE_DATA"); return; } final InputStream streamData = httpRequest.getStreamData(); if (streamData != null) { recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "STREAM_DATA"); return; } final EntityWriter entityWriter = httpRequest.getEntityWriter(); if (entityWriter != null) { recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, "STREAM_DATA"); return; } } /** * record http multipart data * * @param httpRequest * @param recorder */ protected void recordMultipartData(final com.ning.http.client.Request httpRequest, final SpanEventRecorder recorder) { List<Part> parts = httpRequest.getParts(); if (parts != null && parts.isEmpty()) { StringBuilder sb = new StringBuilder(entityDumpSize * 2); Iterator<Part> iterator = parts.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (part instanceof com.ning.http.client.ByteArrayPart) { com.ning.http.client.ByteArrayPart p = (com.ning.http.client.ByteArrayPart) part; sb.append(part.getName()); sb.append("=BYTE_ARRAY_"); sb.append(p.getData().length); } else if (part instanceof com.ning.http.client.FilePart) { com.ning.http.client.FilePart p = (com.ning.http.client.FilePart) part; sb.append(part.getName()); sb.append("=FILE_"); sb.append(p.getMimeType()); } else if (part instanceof com.ning.http.client.StringPart) { com.ning.http.client.StringPart p = (com.ning.http.client.StringPart) part; sb.append(part.getName()); sb.append("="); sb.append(p.getValue()); } else if (part instanceof com.ning.http.multipart.FilePart) { com.ning.http.multipart.FilePart p = (com.ning.http.multipart.FilePart) part; sb.append(part.getName()); sb.append("=FILE_"); sb.append(p.getContentType()); } else if (part instanceof com.ning.http.multipart.StringPart) { com.ning.http.multipart.StringPart p = (com.ning.http.multipart.StringPart) part; sb.append(part.getName()); // Ignore value because there's no way to get string value and StringPart is an adaptation class of Apache HTTP client. sb.append("=STRING"); } if (sb.length() >= entityDumpSize) { break; } if (iterator.hasNext()) { sb.append(","); } } recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, StringUtils.drop(sb.toString(), entityDumpSize)); } } /** * record http request parameter * * @param httpRequest * @param recorder */ protected void recordParam(final com.ning.http.client.Request httpRequest, final SpanEventRecorder recorder) { if (paramSampler.isSampling()) { FluentStringsMap requestParams = httpRequest.getParams(); if (requestParams != null) { String params = paramsToString(requestParams, paramDumpSize); recorder.recordAttribute(AnnotationKey.HTTP_PARAM, StringUtils.drop(params, paramDumpSize)); } } } /** * Returns string without double quotations marks, spaces, semi-colons from com.ning.http.client.FluentStringsMap.toString() * * @param params * @param limit * @return */ private String paramsToString(FluentStringsMap params, int limit) { StringBuilder result = new StringBuilder(limit * 2); for (Map.Entry<String, List<String>> entry : params.entrySet()) { if (result.length() > 0) { result.append(","); } result.append(entry.getKey()); result.append("="); boolean needsComma = false; for (String value : entry.getValue()) { if (needsComma) { result.append(", "); } else { needsComma = true; } result.append(value); } if (result.length() >= limit) { break; } } return result.toString(); } @Override public void setTraceContext(TraceContext traceContext) { this.traceContext = traceContext; final ProfilerConfig profilerConfig = traceContext.getProfilerConfig(); this.dumpCookie = profilerConfig.isNingAsyncHttpClientProfileCookie(); this.cookieDumpType = profilerConfig.getNingAsyncHttpClientProfileCookieDumpType(); this.cookieDumpSize = profilerConfig.getNingAsyncHttpClientProfileCookieDumpSize(); if (dumpCookie) { this.cookieSampler = SimpleSamplerFactory.createSampler(dumpCookie, profilerConfig.getNingAsyncHttpClientProfileCookieSamplingRate()); } this.dumpEntity = profilerConfig.isNingAsyncHttpClientProfileEntity(); this.entityDumpType = profilerConfig.getNingAsyncHttpClientProfileEntityDumpType(); this.entityDumpSize = profilerConfig.getNingAsyncHttpClientProfileEntityDumpSize(); if (dumpEntity) { this.entitySampler = SimpleSamplerFactory.createSampler(dumpEntity, profilerConfig.getNingAsyncHttpClientProfileEntitySamplingRate()); } this.dumpParam = profilerConfig.isNingAsyncHttpClientProfileParam(); this.paramDumpType = profilerConfig.getNingAsyncHttpClientProfileParamDumpType(); this.paramDumpSize = profilerConfig.getNingAsyncHttpClientProfileParamDumpSize(); if (dumpParam) { this.paramSampler = SimpleSamplerFactory.createSampler(dumpParam, profilerConfig.getNingAsyncHttpClientProfileParamSamplingRate()); } } @Override public void setMethodDescriptor(MethodDescriptor descriptor) { this.descriptor = descriptor; traceContext.cacheApi(descriptor); } }
/* * Reads the XMl and generates the connection objects(Not the physical connections) */ package craptor.parser; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import craptor.core.EnvConnection; public class ConnectionsFileHandler { private javax.xml.parsers.DocumentBuilder parser; private Document document; private String fileName; private ConnectionsFileHandler(String fileName) throws Exception { this.fileName = fileName; // Get a JAXP parser factory object javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Tell the factory what kind of parser we want dbf.setValidating(false); // Use the factory to get a JAXP parser object parser = dbf.newDocumentBuilder(); // Tell the parser how to handle errors. Note that in the JAXP API, // DOM parsers rely on the SAX API for error handling parser.setErrorHandler(new org.xml.sax.ErrorHandler() { public void warning(SAXParseException e) { System.err.println("WARNING: " + e.getMessage()); } public void error(SAXParseException e) { System.err.println("ERROR: " + e.getMessage()); } public void fatalError(SAXParseException e) throws SAXException { System.err.println("FATAL: " + e.getMessage()); throw e; // re-throw the error } }); //Parse the xml file and get the document document = parser.parse(new File(fileName)); } public static ConnectionsFileHandler getInstance(String fileName) throws Exception { return new ConnectionsFileHandler(fileName); } /** * Traverse through document and creates the connection objects * @return * @throws Exception */ public List<EnvConnection> getConnections() throws Exception { List<EnvConnection> connections = new ArrayList<EnvConnection>(); Node node = document.getFirstChild(); NodeList nodes = node.getChildNodes(); // Gets the connection for(int i = 0; i < nodes.getLength(); ++i) // Loop through connection { Node childNode = nodes.item(i); NamedNodeMap attr; if((attr = childNode.getAttributes()) != null){ String connectionName = attr.getNamedItem("name").getTextContent(); EnvConnection conn = new EnvConnection(connectionName); NodeList childNodes = childNode.getChildNodes(); for(int j = 0; j < childNodes.getLength(); ++j) // Lop for host, port ..etc.. { Node subChildNode = childNodes.item(j); String nodeName = subChildNode.getNodeName(); String value = subChildNode.getTextContent().trim(); if("host".equals(nodeName)) { conn.setHost(value); } else if("port".equals(nodeName)) { conn.setPort(value); } else if("sid".equals(nodeName)) { conn.setSid(value); } else if("username".equals(nodeName)) { conn.setUserName(value); } else if("password".equals(nodeName)) { conn.setPassword(value); } else if("url".equals(nodeName)) { conn.setUrl(value); } else if("dbtype".equals(nodeName)) { conn.setDbtype(value); } } connections.add(conn); } } return connections; } /** * Adds the connection to document * @param conn */ public void addConnection(EnvConnection conn){ Element connection = document.createElement("connection"); connection.setAttribute("name",conn.getName()); Element host = document.createElement("host"); host.insertBefore(document.createTextNode(conn.getHost()), host.getFirstChild()); Element port = document.createElement("port"); port.insertBefore(document.createTextNode(conn.getPort()), port.getFirstChild()); Element sid = document.createElement("sid"); sid.insertBefore(document.createTextNode(conn.getSid()), sid.getFirstChild()); Element username = document.createElement("username"); username.insertBefore(document.createTextNode(conn.getUserName()), username.getFirstChild()); Element password = document.createElement("password"); password.insertBefore(document.createTextNode(conn.getPassword()), password.getFirstChild()); Element url = document.createElement("url"); url.insertBefore(document.createTextNode(conn.getUrl()), url.getFirstChild()); Element dbType = document.createElement("dbType"); dbType.insertBefore(document.createTextNode(conn.getDbtype()), dbType.getFirstChild()); connection.insertBefore(host,connection.getFirstChild()); connection.insertBefore(port,connection.getFirstChild().getNextSibling()); connection.insertBefore(sid,connection.getFirstChild().getNextSibling()); connection.insertBefore(username,connection.getFirstChild().getNextSibling()); connection.insertBefore(password, connection.getFirstChild().getNextSibling()); connection.insertBefore(url, connection.getFirstChild().getNextSibling()); connection.insertBefore(dbType, connection.getFirstChild().getNextSibling()); document.getFirstChild().appendChild(connection); try { saveFile(); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Deletes the connections from document * @param connName */ public void deleteConnection(String connName){ NodeList connections = document.getElementsByTagName("connection"); int len = connections.getLength(); // try to remove this loop by placing ID attr in connection tag... document.getElementById for(int i = 0; i < len; ++i) { Node node = connections.item(i); System.out.println(node.getAttributes().getNamedItem("name")); String name = node.getAttributes().getNamedItem("name").getTextContent(); if(connName.equals(name)){ node.getParentNode().removeChild(node); break; } } document.normalize(); try { saveFile(); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Saves the document to the file * @throws FileNotFoundException */ public void saveFile() throws FileNotFoundException { XMLDocumentWriter writer = new XMLDocumentWriter(new PrintWriter(fileName)); writer.write(document); writer.close(); } /*public static void main(String[] args) { ConnectionsFileHandler parser; try { parser = ConnectionsFileHandler.getInstance("connections1.xml"); ArrayList list = parser.getConnections(); for(int i = 0 ; i < list.size(); ++i) { System.out.println(((EnvConnection)list.get(i)).getConnectionString()); } parser.deleteConnection("IGSD2RM"); XMLDocumentWriter writer = new XMLDocumentWriter(new PrintWriter("connections1.xml")); writer.write(parser.document); writer.close(); } catch (Exception e) { e.printStackTrace(); } }*/ }
/* (C) 2012 Pragmatic Software This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.chrisplus.ltm.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.zip.ZipInputStream; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.Build; import android.util.Log; import com.chrisplus.ltm.R; import com.chrisplus.ltm.activies.ErrorDialogActivity; public class SysUtils { private final static String TAG = SysUtils.class.getSimpleName(); private static String iptablesBinary; private static String iptablesMd5; private static int iptablesResource; private static String grepBinary; private static String grepMd5; private static int grepResource; private static String nflogBinary; private static String nflogMd5; private static int nflogResource; public static boolean getBinariesIdentifiers() { String cpu_abi = Build.CPU_ABI.toLowerCase(); if (cpu_abi.contains("armeabi-v7")) { iptablesBinary = "iptables_armv7"; iptablesMd5 = "5515873b7ce1617f3d724a3332c2b947"; iptablesResource = R.raw.iptables_armv7; grepBinary = "grep_armv7"; grepMd5 = "69d0726f2b314a32fcd906a753deaabb"; grepResource = R.raw.grep_armv7; nflogBinary = "nflog_armv7"; nflogMd5 = "286eb86e340610727b262593e75e8939"; nflogResource = R.raw.nflog_armv7; } else if (cpu_abi.contains("armeabi")) { iptablesBinary = "iptables_armv5"; iptablesMd5 = "50e39f66369344b692084a9563c185d4"; iptablesResource = R.raw.iptables_armv5; grepBinary = "grep_armv5"; grepMd5 = "7904ae3e4f310f9a1bf9867cfadb71ef"; grepResource = R.raw.grep_armv5; nflogBinary = "nflog_armv5"; nflogMd5 = "509e613ca8734a6bcc6d3327298a9320"; nflogResource = R.raw.nflog_armv5; } else if (cpu_abi.contains("x86")) { iptablesBinary = "iptables_x86"; iptablesMd5 = "3e7090f93ae3964c98e16016b742acbc"; iptablesResource = R.raw.iptables_x86; grepBinary = "grep_x86"; grepMd5 = "75210f186d666f32a14d843fd1e9fac5"; grepResource = R.raw.grep_x86; nflogBinary = "nflog_x86"; nflogMd5 = "0bc6661f7cc3de8c875e021229effb1d"; nflogResource = R.raw.nflog_x86; } else if (cpu_abi.contains("mips")) { iptablesBinary = "iptables_mips"; iptablesMd5 = "c208f8f9a6fa8d7b436c069b71299668"; iptablesResource = R.raw.iptables_mips; grepBinary = "grep_mips"; grepMd5 = "a29534a420f9eb9cc519088eacf6b7e7"; grepResource = R.raw.grep_mips; nflogBinary = "nflog_mips"; nflogMd5 = "86574f4085b3ab74d01c4e3d2ecb1c91"; nflogResource = R.raw.nflog_mips; } else { iptablesBinary = null; grepBinary = null; nflogBinary = null; return false; } return true; } public static String getIptablesBinary() { if (iptablesBinary == null) { getBinariesIdentifiers(); } return iptablesBinary; } public static String getGrepBinary() { if (grepBinary == null) { getBinariesIdentifiers(); } return grepBinary; } public static String getNflogBinary() { if (nflogBinary == null) { getBinariesIdentifiers(); } return nflogBinary; } public static boolean installBinary(Context context, String binary, String md5sum, int resource, String path) { boolean needsInstall = false; File file = new File(path); if (file.isFile()) { String hash = MD5Sum.digestFile(file); if (!hash.equals(md5sum)) { needsInstall = true; } } else { needsInstall = true; } if (needsInstall) { try { Log.d(TAG, binary + " not found: installing to " + path); InputStream raw = context.getResources().openRawResource(resource); ZipInputStream zip = new ZipInputStream(raw); zip.getNextEntry(); InputStream in = zip; FileOutputStream out = new FileOutputStream(path); byte buf[] = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.close(); in.close(); Runtime.getRuntime().exec("chmod 755 " + path).waitFor(); } catch (Exception e) { Resources res = context.getResources(); showError(context, res.getString(R.string.error_default_title), String.format(res.getString(R.string.error_install_binary_text), binary) + e.getMessage()); return false; } } else { Log.d(TAG, binary + " found at " + path); } return true; } public static boolean installBinaries(Context context) { if (!getBinariesIdentifiers()) { Resources res = context.getResources(); showError(context, res.getString(R.string.error_unsupported_system_title), String.format(res.getString(R.string.error_unsupported_system_text), Build.CPU_ABI)); return false; } String iptablesPath = context.getFilesDir().getAbsolutePath() + File.separator + iptablesBinary; if (!installBinary(context, iptablesBinary, iptablesMd5, iptablesResource, iptablesPath)) { return false; } String grepPath = context.getFilesDir().getAbsolutePath() + File.separator + grepBinary; if (!installBinary(context, grepBinary, grepMd5, grepResource, grepPath)) { return false; } String nflogPath = context.getFilesDir().getAbsolutePath() + File.separator + nflogBinary; if (!installBinary(context, nflogBinary, nflogMd5, nflogResource, nflogPath)) { return false; } return true; } public static void showError(final Context context, final String title, final String message) { Log.d("NetworkLog", "Got error: [" + title + "] [" + message + "]"); context.startActivity(new Intent(context, ErrorDialogActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra("title", title) .putExtra("message", message)); } public static boolean isServiceRunning(Context context, String serviceClassName) { final ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager .getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)) { return true; } } return false; } public static void checkFileEnvironment(String fileName) { File path = new File(Constants.LOG_PATH); if (!path.exists()) { path.mkdirs(); } File file = new File(Constants.LOG_PATH + fileName); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * */ package gov.nih.nci.cagrid.portal.portlet.browse.sharedQuery; import gov.nih.nci.cagrid.common.SchemaValidationException; import gov.nih.nci.cagrid.common.SchemaValidator; import gov.nih.nci.cagrid.common.Utils; import gov.nih.nci.cagrid.portal.dao.QueryDao; import gov.nih.nci.cagrid.portal.dao.catalog.GridServiceEndPointCatalogEntryDao; import gov.nih.nci.cagrid.portal.dao.catalog.SharedQueryCatalogEntryDao; import gov.nih.nci.cagrid.portal.domain.catalog.CatalogEntry; import gov.nih.nci.cagrid.portal.domain.catalog.GridServiceEndPointCatalogEntry; import gov.nih.nci.cagrid.portal.domain.catalog.SharedQueryCatalogEntry; import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQuery; import gov.nih.nci.cagrid.portal.domain.dataservice.DCQLQuery; import gov.nih.nci.cagrid.portal.domain.dataservice.Query; import gov.nih.nci.cagrid.portal.portlet.browse.GridServiceEndpointDescriptorBean; import gov.nih.nci.cagrid.portal.portlet.browse.ajax.ToolCatalogEntryManagerFacade; import gov.nih.nci.cagrid.portal.portlet.util.PortletUtils; import gov.nih.nci.cagrid.portal.util.PortalUtils; import org.apache.axis.utils.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a> * @author kherm manav.kher@semanticbits.com */ @Transactional public class SharedQueryCatalogEntryManagerFacade extends ToolCatalogEntryManagerFacade { private int maxActiveQueries; private GridServiceEndPointCatalogEntryDao gridServiceEndPointCatalogEntryDao; private String queryXML; private SharedQueryCatalogEntryDao sharedQueryCatalogEntryDao; private QueryDao queryDao; private String selectEndpointsFormContentViewName; String cqlSchema, dcqlSchema; private static final Log logger = LogFactory .getLog(SharedQueryCatalogEntryManagerFacade.class); /** * */ public SharedQueryCatalogEntryManagerFacade() { } public String setQuery(String queryXML) { this.queryXML = queryXML.trim(); return null; } /** * for autocompleterer. Will only get services that are associated with CE's * * @param partialUrl * @return */ public List<GridServiceEndpointDescriptorBean> getCatalogEntriesForPartialUrl( String partialUrl) { List<GridServiceEndpointDescriptorBean> result = new ArrayList<GridServiceEndpointDescriptorBean>(); for (GridServiceEndPointCatalogEntry entry : gridServiceEndPointCatalogEntryDao .getByPartialUrl(partialUrl)) { GridServiceEndpointDescriptorBean descriptor = new GridServiceEndpointDescriptorBean( String.valueOf(entry.getId()), String.valueOf(entry .getAbout().getId()), entry.getAbout().getUrl()); result.add(descriptor); } return result; } public List<GridServiceEndpointDescriptorBean> getAppropriateEndpointsForPartialUrl( String xml, String partialUrl) { List<GridServiceEndpointDescriptorBean> result = new ArrayList<GridServiceEndpointDescriptorBean>(); if (StringUtils.isEmpty(xml)) { logger.debug("xml is null, ignoring request"); } else { List<GridServiceEndPointCatalogEntry> endpointCes = null; if (PortletUtils.isCQL(xml)) { logger.debug("this is a CQL query"); String umlClassName = PortletUtils.getTargetUMLClassName(xml); logger.debug("UMLClass: " + umlClassName); int idx = umlClassName.lastIndexOf("."); String packageName = umlClassName.substring(0, idx); String className = umlClassName.substring(idx + 1); endpointCes = getGridServiceEndPointCatalogEntryDao() .getByUmlClassNameAndPartialUrl(packageName, className, partialUrl); } else { logger.debug("this is a DCQL query"); endpointCes = getGridServiceEndPointCatalogEntryDao() .getByPartialUrl(partialUrl); } for (GridServiceEndPointCatalogEntry entry : endpointCes) { GridServiceEndpointDescriptorBean descriptor = new GridServiceEndpointDescriptorBean( String.valueOf(entry.getId()), String.valueOf(entry .getAbout().getId()), entry.getAbout().getUrl()); result.add(descriptor); } } return result; } @Override public String validate() { String message = null; /** must validate as CQL or DCQL **/ try { URL schemaPath = this.getClass().getClassLoader().getResource(getCqlSchema()); SchemaValidator validator = new SchemaValidator(schemaPath.getFile()); validator.validate(this.queryXML); } catch (SchemaValidationException e) { try { URL dcqlSchema = this.getClass().getClassLoader().getResource(getDcqlSchema()); SchemaValidator validator = new SchemaValidator(dcqlSchema.getFile()); validator.validate(this.queryXML); } catch (SchemaValidationException e1) { logger.warn("Saving invalid query " + e1.getMessage()); message = "The query is invalid. Please check the syntax."; } } return message; } public String getTargetClass() { String queryXML = ((SharedQueryCatalogEntry) getUserModel() .getCurrentCatalogEntry()).getAbout().getXml(); StringReader reader = new StringReader(queryXML); try { gov.nih.nci.cagrid.cqlquery.CQLQuery query = (gov.nih.nci.cagrid.cqlquery.CQLQuery) Utils .deserializeObject(reader, gov.nih.nci.cagrid.cqlquery.CQLQuery.class); return query.getTarget().getName(); } catch (Exception e) { return "Could not be determined"; } } public String renderAvailableEndpointsFormContent(String cql, String ns) { Map<String, Object> reqAttributes = new HashMap<String, Object>(); reqAttributes.put("ns", ns); try { reqAttributes.put("endpoints", getAvailableEndpoints(cql)); return getView(getSelectEndpointsFormContentViewName(), reqAttributes); } catch (Exception ex) { String msg = "Error rendering select endpoints form content: " + ex.getMessage(); logger.error(msg, ex); throw new RuntimeException(msg, ex); } } public List<GridServiceEndPointCatalogEntry> getAvailableEndpoints(String cql) { List<GridServiceEndPointCatalogEntry> endpointCes = null; if (PortletUtils.isCQL(cql)) { String umlClassName = PortletUtils.getTargetUMLClassName(cql); int idx = umlClassName.lastIndexOf("."); String packageName = umlClassName.substring(0, idx); String className = umlClassName.substring(idx + 1); endpointCes = getGridServiceEndPointCatalogEntryDao() .getByUmlClassNameAndPartialUrl(packageName, className, "%"); } else { endpointCes = getGridServiceEndPointCatalogEntryDao() .getByPartialUrl("FederatedQueryProcessor"); } return endpointCes; } @Override protected Integer saveInternal(CatalogEntry catalogEntry) { SharedQueryCatalogEntry sqCe = (SharedQueryCatalogEntry) catalogEntry; if (this.queryXML != null) { String xml = null; if (PortletUtils.isCQL(queryXML)) { xml = PortletUtils.normalizeCQL(queryXML); } else { xml = PortletUtils.normalizeDCQL(queryXML); } String hash = PortalUtils.createHash(xml); Query aboutQuery = sqCe.getAbout(); if (aboutQuery == null) { aboutQuery = getQueryDao().getQueryByHash(hash); if (aboutQuery == null) { logger.debug("Will create a new query"); if (PortletUtils.isCQL(queryXML)) { aboutQuery = new CQLQuery(); } else { aboutQuery = new DCQLQuery(); } } sqCe.setAbout(aboutQuery); } else { aboutQuery = getQueryDao().getById(aboutQuery.getId()); } aboutQuery.setHash(hash); aboutQuery.setXml(xml); getQueryDao().save(aboutQuery); getSharedQueryCatalogEntryDao().save(sqCe); } return sqCe.getId(); } public String getCqlSchema() { return cqlSchema; } public void setCqlSchema(String cqlSchema) { this.cqlSchema = cqlSchema; } public String getDcqlSchema() { return dcqlSchema; } public void setDcqlSchema(String dcqlSchema) { this.dcqlSchema = dcqlSchema; } public GridServiceEndPointCatalogEntryDao getGridServiceEndPointCatalogEntryDao() { return gridServiceEndPointCatalogEntryDao; } @Required public void setGridServiceEndPointCatalogEntryDao( GridServiceEndPointCatalogEntryDao gridServiceEndPointCatalogEntryDao) { this.gridServiceEndPointCatalogEntryDao = gridServiceEndPointCatalogEntryDao; } public SharedQueryCatalogEntryDao getSharedQueryCatalogEntryDao() { return sharedQueryCatalogEntryDao; } @Required public void setSharedQueryCatalogEntryDao( SharedQueryCatalogEntryDao sharedQueryCatalogEntryDao) { this.sharedQueryCatalogEntryDao = sharedQueryCatalogEntryDao; } public QueryDao getQueryDao() { return queryDao; } @Required public void setQueryDao(QueryDao queryDao) { this.queryDao = queryDao; } public String getSelectEndpointsFormContentViewName() { return selectEndpointsFormContentViewName; } public void setSelectEndpointsFormContentViewName( String selectEndpointsFormContentViewName) { this.selectEndpointsFormContentViewName = selectEndpointsFormContentViewName; } public int getMaxActiveQueries() { return maxActiveQueries; } @Required public void setMaxActiveQueries(int maxActiveQueries) { this.maxActiveQueries = maxActiveQueries; } }
/****************************************************** Copyright (c) 2015, IBM Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *********************************************************/ package com.ibm.si.qradar.offenseviz.core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.persistence.EntityManager; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.ibm.si.qradar.offenseviz.conf.QRadarConfig; import com.ibm.si.qradar.offenseviz.dao.DestinationDao; import com.ibm.si.qradar.offenseviz.dao.OffenseDao; import com.ibm.si.qradar.offenseviz.dao.SourceDao; import com.ibm.si.qradar.offenseviz.geoip.GeoInfo; import com.ibm.si.qradar.offenseviz.geoip.GeoipUtil; import com.ibm.si.qradar.offenseviz.jpa.Destination; import com.ibm.si.qradar.offenseviz.jpa.GeographicEndpoint; import com.ibm.si.qradar.offenseviz.jpa.Offense; import com.ibm.si.qradar.offenseviz.jpa.Source; import com.ibm.si.qradar.offenseviz.util.PersistenceUtil; public class OffenseCollector implements Runnable { private static final Logger logger = LoggerFactory.getLogger(OffenseCollector.class); private static final String OFFENSE_API_PATH = "/api/siem/offenses"; private static final String SOURCE_API_PATH = "/api/siem/source_addresses"; private static final String DEST_API_PATH = "/api/siem/local_destination_addresses"; private final Double defaultLatitude; private final Double defaultLongitude; private final String defaultCountry; private final String defaultCity; private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); private enum EntityType { SOURCE, DEST }; private OffenseDao offenseDao; private SourceDao sourceDao; private DestinationDao destDao; private GeoipUtil geoipUtil = null; ObjectMapper mapper; public OffenseCollector() { defaultLatitude = QRadarConfig.getInstance().getDefaultLatitude(); defaultLongitude = QRadarConfig.getInstance().getDefaultLongitude(); defaultCountry = QRadarConfig.getInstance().getDefaultCountry(); defaultCity = QRadarConfig.getInstance().getDefaultCity(); } @Override public void run() { EntityManager entityManager = null; try { geoipUtil = new GeoipUtil(); mapper = new ObjectMapper(); entityManager = PersistenceUtil.getEntityManagerFactory().createEntityManager(); offenseDao = new OffenseDao(entityManager); sourceDao = new SourceDao(entityManager); destDao = new DestinationDao(entityManager); getOffenses(); } catch (Exception e) { logger.error("Could not get offense list from QRadar", e); } finally { if(entityManager != null) { entityManager.close(); } if(geoipUtil != null) { geoipUtil.dispose(); } } } public void getOffenses() throws Exception { Date now = new Date(); Timestamp timestamp = new Timestamp(now.getTime()); logger.debug("Grabbing offenses at " + dateFormat.format(now)); String authToken = QRadarConfig.getInstance().getAuthorizationToken(); CloseableHttpClient httpclient = getHttpClient(); URI uri = getURI(OFFENSE_API_PATH); String json = executeGet(uri, httpclient, authToken); Date after = new Date(); logger.debug("Returned with offenses from QRadar at " + dateFormat.format(after)); logger.debug("It took " + (after.getTime() - now.getTime()) + " milliseconds to retrieve those offenses"); processOffenses(json, timestamp); } private String getSourcesOrDestsById(Set<Integer> ids, EntityType type) throws Exception { String path; if (type == EntityType.SOURCE) { path = SOURCE_API_PATH; } else { path = DEST_API_PATH; } String authToken = QRadarConfig.getInstance().getAuthorizationToken(); CloseableHttpClient httpclient = getHttpClient(); String filter = buildIdFilter(ids); String qradarUrl = QRadarConfig.getInstance().getUrl(); URI uri = new URIBuilder().setScheme("https") .setHost(qradarUrl) .setPath(path) .setParameter("filter", filter) .build(); String json = executeGet(uri, httpclient, authToken); return json; } private List<Source> updateSources(Set<Integer> ids) throws Exception{ Date before = new Date(); logger.debug("Getting sources at " + dateFormat.format(before)); String json = getSourcesOrDestsById(ids, EntityType.SOURCE); List<Source> sources = mapper.readValue(json, mapper.getTypeFactory() .constructCollectionType(List.class, Source.class)); List<Source> mergedSources = new ArrayList<Source>(); for(Source source : sources) { updateGeographicInfo(source); mergedSources.add(sourceDao.merge(source)); } Date after = new Date(); logger.debug("Sources retrieved at " + dateFormat.format(after)); logger.debug(String.valueOf(sources.size()) + " sources were processed in " + (after.getTime() - before.getTime()) + " milliseconds"); return mergedSources; } private List<Destination> updateDestinations(Set<Integer> ids) throws Exception { Date before = new Date(); logger.debug("Getting destinations at " + dateFormat.format(before)); String json = getSourcesOrDestsById(ids, EntityType.DEST); List<Destination> dests = mapper.readValue(json, mapper.getTypeFactory() .constructCollectionType(List.class, Destination.class)); List<Destination> mergedDests = new ArrayList<Destination>(); for(Destination dest: dests) { updateGeographicInfo(dest); mergedDests.add(destDao.merge(dest)); } Date after = new Date(); logger.debug("Destinations retrieved at " + dateFormat.format(after)); logger.debug(String.valueOf(dests.size()) + " destinations were processed in " + (after.getTime() - before.getTime()) + " milliseconds"); return mergedDests; } private void updateGeographicInfo(GeographicEndpoint endpoint) throws Exception{ GeoInfo ginfo = geoipUtil.getGeoInfo(endpoint.getIp()); if(ginfo == null) { logger.debug("Could not lookup ip " + endpoint.getIp()); endpoint.setLatitude(defaultLatitude); endpoint.setLongitude(defaultLongitude); endpoint.setCountry(defaultCountry); endpoint.setCity(defaultCity); endpoint.setInternal(false); } else { logger.debug("Successfully looked up ip " + endpoint.getIp()); endpoint.setLatitude(ginfo.getLatitude()); endpoint.setLongitude(ginfo.getLongitude()); endpoint.setCountry(ginfo.getCountry()); endpoint.setCity(ginfo.getCity()); endpoint.setInternal(false); } } private String buildIdFilter(Set<Integer> ids) { String filterPrefix = "id in %s"; String idString = StringUtils.join((Object) ids); String formattedIds = idString .replace("[", "(") .replace("]", ")") .trim(); String filter = String.format(filterPrefix, formattedIds); return filter; } private void processOffenses(String json, Timestamp timestamp) throws Exception { List<Offense> offenses = mapper.readValue(json, mapper.getTypeFactory() .constructCollectionType(List.class, Offense.class)); logger.debug("Processing " + String.valueOf(offenses.size()) + " offenses at " + dateFormat.format(new Date())); for (Offense offense : offenses) { offense.setSeenAt(timestamp); offense.setSourceList(new ArrayList<Source>()); offense.setDestinationList(new ArrayList<Destination>()); for (Integer id : offense.getSourceIds()) { Source source = new Source(id); offense.getSourceList().add(sourceDao.merge(source)); } for (Integer id : offense.getDestIds()) { Destination dest = new Destination(id); offense.getDestinationList().add(destDao.merge(dest)); } offenseDao.persist(offense); } updateSourcesAndDests(offenses); } private void updateSourcesAndDests(List<Offense> offenses) { Set<Integer> sourceIdSet = new HashSet<Integer>(); Set<Integer> destIdSet = new HashSet<Integer>(); for (Offense offense : offenses) { sourceIdSet.addAll(offense.getSourceIds()); destIdSet.addAll(offense.getDestIds()); } try { updateSources(sourceIdSet); updateDestinations(destIdSet); } catch (Exception e) { logger.error("Failed to update offense sources and dests", e); } } private String executeGet(URI uri, CloseableHttpClient httpclient, String authToken) throws ClientProtocolException, IOException { HttpGet httpget = new HttpGet(uri); httpget.addHeader("SEC", authToken); CloseableHttpResponse response = httpclient.execute(httpget); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); response.close(); return json; } private CloseableHttpClient getHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { CloseableHttpClient httpclient = HttpClients.custom(). setHostnameVerifier(new AllowAllHostnameVerifier()). setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build()).build(); return httpclient; } private URI getURI(String path) throws URISyntaxException { String qradarUrl = QRadarConfig.getInstance().getUrl(); URI uri = new URIBuilder().setScheme("https") .setHost(qradarUrl) .setPath(path) .addParameter("filter", "inactive=false and status=\"OPEN\"") .build(); return uri; } }
/* * (C) Copyright Itude Mobile B.V., The Netherlands * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.itude.mobile.mobbl.core.services; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.enterprise.inject.Alternative; import javax.faces.context.FacesContext; import org.apache.log4j.Logger; import com.itude.mobile.mobbl.core.configuration.mvc.MBActionDefinition; import com.itude.mobile.mobbl.core.configuration.mvc.MBConfigurationDefinition; import com.itude.mobile.mobbl.core.configuration.mvc.MBDialogDefinition; import com.itude.mobile.mobbl.core.configuration.mvc.MBDocumentDefinition; import com.itude.mobile.mobbl.core.configuration.mvc.MBDomainDefinition; import com.itude.mobile.mobbl.core.configuration.mvc.MBMvcConfigurationParser; import com.itude.mobile.mobbl.core.configuration.mvc.MBOutcomeDefinition; import com.itude.mobile.mobbl.core.configuration.mvc.MBPageDefinition; import com.itude.mobile.mobbl.core.services.exceptions.MBActionNotDefinedException; import com.itude.mobile.mobbl.core.services.exceptions.MBDialogNotDefinedException; import com.itude.mobile.mobbl.core.services.exceptions.MBDocumentNotDefinedException; import com.itude.mobile.mobbl.core.services.exceptions.MBDomainNotDefinedException; import com.itude.mobile.mobbl.core.services.exceptions.MBPageNotDefinedException; /** * Service class for working with Model, View and Controller definition objects. * Use this class to: * <ul> * <li>Set which configuration and webservice-endpoint files to use.</li> * <li>Retrieve definitions for programmatically creating MBDocument, MBDomain, MBDomainValidator objects.</li> * </ul> */ @Alternative public class MBMetadataService implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(MBMetadataService.class); private final MBConfigurationDefinition _cfg; private static MBMetadataService _instance; private static final String CONFIG_NAME = "config"; private Map<String, Object> getRequestMap() { return FacesContext.getCurrentInstance().getExternalContext().getRequestMap(); } private MBMetadataService() { MBMvcConfigurationParser parser = new MBMvcConfigurationParser(); _cfg = (MBConfigurationDefinition) parser.parseData(MBResourceService.getInstance().getResourceByID(CONFIG_NAME), CONFIG_NAME); } public static MBMetadataService getInstance() { if (_instance == null) { _instance = new MBMetadataService(); } return _instance; } public MBDomainDefinition getDefinitionForDomainName(String domainName) { return getDefinitionForDomainName(domainName, true); } public MBDomainDefinition getDefinitionForDomainName(String domainName, boolean doThrow) { // Pjotter: fun! ^_^ The domain definitions are modified in some controllers, and we don't really // want to do this over the entire application. While this can be done more nicely, it would // cause major differences between the android and the JSF applications. // Therefore, the definitions are transparently stored in the current request scope when // requested. String key = "DOMAINDEFINITION_" + domainName; MBDomainDefinition domDef; domDef = (MBDomainDefinition) getRequestMap().get(key); if (domDef == null) { domDef = _cfg.getDefinitionForDomainName(domainName); if (domDef != null) getRequestMap().put(key, domDef); } if (domDef == null && doThrow) { String message = "Domain with name " + domainName + " not defined"; throw new MBDomainNotDefinedException(message); } return domDef; } public MBPageDefinition getDefinitionForPageName(String pageName) { return getDefinitionForPageName(pageName, true); } public MBPageDefinition getDefinitionForPageName(String pageName, boolean doThrow) { MBPageDefinition pageDef = _cfg.getDefinitionForPageName(pageName); if (pageDef == null && doThrow) { String message = "Page with name " + pageName + " not defined"; throw new MBPageNotDefinedException(message); } return pageDef; } public MBActionDefinition getDefinitionForActionName(String actionName) { return getDefinitionForActionName(actionName, true); } public MBActionDefinition getDefinitionForActionName(String actionName, boolean doThrow) { MBActionDefinition actionDef = _cfg.getDefinitionForActionName(actionName); if (actionDef == null && doThrow) { String message = "Action with name " + actionName + " not defined"; throw new MBActionNotDefinedException(message); } return actionDef; } public MBDocumentDefinition getDefinitionForDocumentName(String documentName) { return getDefinitionForDocumentName(documentName, true); } public MBDocumentDefinition getDefinitionForDocumentName(String documentName, boolean doThrow) { MBDocumentDefinition docDef = _cfg.getDefinitionForDocumentName(documentName); if (docDef == null && doThrow) { String message = "Document with name " + documentName + " not defined"; throw new MBDocumentNotDefinedException(message); } return docDef; } public MBDialogDefinition getDefinitionForDialogName(String dialogName) { return getDefinitionForDialogName(dialogName, true); } public MBDialogDefinition getDefinitionForDialogName(String dialogName, boolean doThrow) { MBDialogDefinition dialogDef = _cfg.getDefinitionForDialogName(dialogName); if (dialogDef == null && doThrow) { String message = "Dialog with name " + dialogName + " not defined"; throw new MBDialogNotDefinedException(message); } return dialogDef; } public MBDialogDefinition getFirstDialogDefinition() { return _cfg.getFirstDialogDefinition(); } public List<MBDialogDefinition> getDialogs() { return new ArrayList<MBDialogDefinition>(_cfg.getDialogs().values()); } //For now do not raise an exception if an outcome is not defined public List<MBOutcomeDefinition> getOutcomeDefinitionsForOrigin(String originName) { ArrayList<MBOutcomeDefinition> list = (ArrayList<MBOutcomeDefinition>) _cfg.getOutcomeDefinitionsForOrigin(originName); if (list == null || list.size() <= 0) { LOGGER.warn("WARNING No outcomes defined for origin " + originName + " "); } return list; } public List<MBOutcomeDefinition> getOutcomeDefinitionsForOrigin(String originName, String outcomeName) { return getOutcomeDefinitionsForOrigin(originName, outcomeName, true); } public List<MBOutcomeDefinition> getOutcomeDefinitionsForOrigin(String originName, String outcomeName, boolean doThrow) { ArrayList<MBOutcomeDefinition> outcomeDefs = (ArrayList<MBOutcomeDefinition>) _cfg.getOutcomeDefinitionsForOrigin(originName, outcomeName); if (outcomeDefs.size() == 0 && doThrow) { String message = "Outcome with originName=" + originName + " outcomeName=" + outcomeName + " not defined"; throw new MBActionNotDefinedException(message); } return outcomeDefs; } public MBConfigurationDefinition getConfiguration() { return _cfg; } }
package it.cavallium.warppi.gui.graphicengine.impl.common; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import it.cavallium.warppi.WarpPI; import it.cavallium.warppi.Platform.ConsoleUtils; import it.cavallium.warppi.device.display.DisplayOutputDevice; import it.cavallium.warppi.gui.graphicengine.BinaryFont; import it.cavallium.warppi.util.Utils; public abstract class RFTFont implements BinaryFont { public boolean[][] rawchars; public int[] chars32; public int minBound = 10; public int maxBound = 0; public int charW; public int charH; public int charS; public int charIntCount; public int[] intervals; public int intervalsTotalSize = 0; public static final int intBits = 31; @SuppressWarnings("unused") private final boolean isResource; public RFTFont(final String fontName) throws IOException { this(fontName, false); } RFTFont(final String fontName, final boolean onlyRaw) throws IOException { isResource = true; load("/font_" + fontName + ".rft", onlyRaw); } public RFTFont(final String path, final String fontName) throws IOException { this(path, fontName, false); } RFTFont(final String path, final String fontName, final boolean onlyRaw) throws IOException { isResource = false; load(path + "/font_" + fontName + ".rft", onlyRaw); } public static RFTFont loadTemporaryFont(final String name) throws IOException { return new BlankRFTFont(name, true); } public static RFTFont loadTemporaryFont(final String path, final String name) throws IOException { return new BlankRFTFont(path, name, true); } @Override public void load(final String path) throws IOException { load(path, false); } private void load(final String path, final boolean onlyRaw) throws IOException { WarpPI.getPlatform().getConsoleUtils().out().println(ConsoleUtils.OUTPUTLEVEL_DEBUG_MIN + 1, "Loading font " + path); loadFont(path); if (!onlyRaw) { chars32 = new int[intervalsTotalSize * charIntCount]; for (int charCompressedIndex = 0; charCompressedIndex < intervalsTotalSize; charCompressedIndex++) { final boolean[] currentChar = rawchars[charCompressedIndex]; if (currentChar == null) { int currentInt = 0; int currentBit = 0; for (int i = 0; i < charS; i++) { if (currentInt * RFTFont.intBits + currentBit >= (currentInt + 1) * RFTFont.intBits) { currentInt += 1; currentBit = 0; } chars32[charCompressedIndex * charIntCount + currentInt] = (chars32[charCompressedIndex * charIntCount + currentInt] << 1) + 1; currentBit += 1; } } else { int currentInt = 0; int currentBit = 0; for (int i = 0; i < charS; i++) { if (currentBit >= RFTFont.intBits) { currentInt += 1; currentBit = 0; } chars32[charCompressedIndex * charIntCount + currentInt] = chars32[charCompressedIndex * charIntCount + currentInt] | (currentChar[i] ? 1 : 0) << currentBit; currentBit++; } } } } WarpPI.getPlatform().gc(); } private void loadFont(String string) throws IOException { if (!string.startsWith("/")) { string = "/" + string; } InputStream res = WarpPI.getPlatform().getStorageUtils().getResourceStream(string); final int[] file = Utils.realBytes(Utils.convertStreamToByteArray(res, res.available())); final int filelength = file.length; if (filelength >= 16) { if (file[0x0] == 114 && file[0x1] == 97 && file[0x2] == 119 && file[0x3] == 0xFF && file[0x8] == 0xFF && file[0xD] == 0xFF) { charW = file[0x4] << 8 | file[0x5]; charH = file[0x6] << 8 | file[0x7]; charS = charW * charH; charIntCount = (int) Math.ceil((double) charS / (double) RFTFont.intBits); minBound = file[0x9] << 24 | file[0xA] << 16 | file[0xB] << 8 | file[0xC]; maxBound = file[0xE] << 24 | file[0xF] << 16 | file[0x10] << 8 | file[0x11]; if (maxBound <= minBound) { maxBound = 66000; //TODO remove it: temp fix } rawchars = new boolean[maxBound - minBound][]; int index = 0x12; while (index < filelength) { try { final int charIndex = file[index] << 8 | file[index + 1]; final boolean[] rawchar = new boolean[charS]; int charbytescount = 0; while (charbytescount * 8 < charS) { charbytescount += 1; } int currentBit = 0; for (int i = 0; i <= charbytescount; i++) { for (int bit = 0; bit < 8; bit++) { if (currentBit >= charS) { break; } rawchar[currentBit] = (file[index + 2 + i] >> 8 - 1 - bit & 0x1) == 1 ? true : false; currentBit++; } } rawchars[charIndex - minBound] = rawchar; index += 2 + charbytescount; } catch (final Exception ex) { ex.printStackTrace(); System.out.println(string); WarpPI.getPlatform().exit(-1); } } } else { throw new IOException(); } } else { throw new IOException(); } findIntervals(); /*int[] screen = new int[rawchars.length * charW * charH]; for (int i = 0; i < rawchars.length; i++) { if (rawchars[i] != null) for (int charX = 0; charX < charW; charX++) { for (int charY = 0; charY < charH; charY++) { int x = i * charW + charX; int y = charY; screen[x + y * rawchars.length * charW] = rawchars[i][charX + charY * charW] ? 0xFF000000 : 0xFFFFFFFF; } } } System.out.println(); System.out.println((('1' & 0xFFFF) - minBound) + "=>"+ (getCharIndexes("1")[0])); this.saveArray(screen, rawchars.length * charW, charH, "N:\\TimedTemp"+string+".png"); System.out.println(); System.out.println(); */ } private void findIntervals() { final LinkedList<int[]> intervals = new LinkedList<>(); int beginIndex = -1; int endIndex = 0; int intervalSize = 0; @SuppressWarnings("unused") final int holeSize = 0; for (int i = 0; i < rawchars.length; i++) { if (rawchars[i] != null) { beginIndex = i; int firstNull = 0; while (i + firstNull < rawchars.length && rawchars[i + firstNull] != null) { firstNull++; } endIndex = beginIndex + firstNull - 1; i = endIndex; if (endIndex >= 0) { intervalSize = endIndex - beginIndex + 1; intervals.add(new int[] { beginIndex, endIndex, intervalSize }); intervalsTotalSize += intervalSize; } beginIndex = -1; } } int lastIndex = 0; final boolean[][] newrawchars = new boolean[intervalsTotalSize][]; for (final int[] interval : intervals) { if (rawchars.length - interval[0] - interval[2] < 0) { System.err.println(interval[0] + "-" + interval[1] + "(" + interval[2] + ")"); System.err.println(rawchars.length - interval[0] - interval[2]); throw new ArrayIndexOutOfBoundsException(); } if (newrawchars.length - (lastIndex - 1) - interval[2] < 0) { System.err.println(newrawchars.length - (lastIndex - 1) - interval[2]); throw new ArrayIndexOutOfBoundsException(); } System.arraycopy(rawchars, interval[0], newrawchars, lastIndex, interval[2]); lastIndex += interval[2]; } rawchars = newrawchars; final int intervalsSize = intervals.size(); this.intervals = new int[intervalsSize * 3]; for (int i = 0; i < intervalsSize; i++) { final int[] interval = intervals.get(i); this.intervals[i * 3 + 0] = interval[0]; this.intervals[i * 3 + 1] = interval[1]; this.intervals[i * 3 + 2] = interval[2]; } } public int[] getCharIndexes(final String txt) { final int l = txt.length(); final int[] indexes = new int[l]; final char[] chars = txt.toCharArray(); for (int i = 0; i < l; i++) { final int originalIndex = (chars[i] & 0xFFFF) - minBound; indexes[i] = compressIndex(originalIndex); } return indexes; } public int getCharIndex(final char c) { final int originalIndex = c & 0xFFFF; return compressIndex(originalIndex); } protected int compressIndex(final int originalIndex) { int compressedIndex = 0; for (int i = 0; i < intervals.length; i += 3) { if (intervals[i] > originalIndex) { break; } else if (originalIndex <= intervals[i + 1]) { compressedIndex += originalIndex - intervals[i]; break; } else { compressedIndex += intervals[i + 2]; } } return compressedIndex; } @SuppressWarnings("unused") private int decompressIndex(final int compressedIndex) { final int originalIndex = 0; int i = 0; for (int intvl = 0; intvl < intervals.length; intvl += 3) { i += intervals[intvl + 2]; if (i == compressedIndex) { return intervals[intvl + 1]; } else if (i > compressedIndex) { return intervals[intvl + 1] - (i - compressedIndex); } } return originalIndex; } @Override public void initialize(final DisplayOutputDevice d) {} @Override public int getStringWidth(final String text) { final int w = charW * text.length(); if (text.length() > 0 && w > 0) { return w; } else { return 0; } } @Override public int getCharacterWidth() { return charW; } @Override public int getCharacterHeight() { return charH; } @Override public boolean isInitialized() { return true; } @Override public int getSkinWidth() { return -1; } @Override public int getSkinHeight() { return -1; } private static class BlankRFTFont extends RFTFont { BlankRFTFont(final String fontName, final boolean onlyRaw) throws IOException { super(fontName, onlyRaw); } public BlankRFTFont(final String path, final String name, final boolean b) throws IOException { super(path, name, b); } @Override public void use(final DisplayOutputDevice d) { } } }
/* * Copyright 2009-2013 by The Regents of the University of California * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * you may obtain a copy of the License from * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hyracks.control.cc.scheduler; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang3.tuple.Pair; import org.apache.hyracks.api.constraints.expressions.LValueConstraintExpression; import org.apache.hyracks.api.constraints.expressions.PartitionCountExpression; import org.apache.hyracks.api.dataflow.ActivityId; import org.apache.hyracks.api.dataflow.ConnectorDescriptorId; import org.apache.hyracks.api.dataflow.IConnectorDescriptor; import org.apache.hyracks.api.dataflow.OperatorDescriptorId; import org.apache.hyracks.api.dataflow.TaskId; import org.apache.hyracks.api.dataflow.connectors.IConnectorPolicy; import org.apache.hyracks.api.dataflow.connectors.IConnectorPolicyAssignmentPolicy; import org.apache.hyracks.api.dataflow.connectors.PipeliningConnectorPolicy; import org.apache.hyracks.api.exceptions.HyracksException; import org.apache.hyracks.api.job.ActivityCluster; import org.apache.hyracks.api.job.ActivityClusterGraph; import org.apache.hyracks.api.partitions.PartitionId; import org.apache.hyracks.control.cc.job.ActivityClusterPlan; import org.apache.hyracks.control.cc.job.ActivityPlan; import org.apache.hyracks.control.cc.job.JobRun; import org.apache.hyracks.control.cc.job.Task; import org.apache.hyracks.control.cc.job.TaskCluster; import org.apache.hyracks.control.cc.job.TaskClusterId; public class ActivityClusterPlanner { private static final Logger LOGGER = Logger.getLogger(ActivityClusterPlanner.class.getName()); private final JobScheduler scheduler; private final Map<PartitionId, TaskCluster> partitionProducingTaskClusterMap; public ActivityClusterPlanner(JobScheduler newJobScheduler) { this.scheduler = newJobScheduler; partitionProducingTaskClusterMap = new HashMap<PartitionId, TaskCluster>(); } public ActivityClusterPlan planActivityCluster(ActivityCluster ac) throws HyracksException { JobRun jobRun = scheduler.getJobRun(); Map<ActivityId, ActivityPartitionDetails> pcMap = computePartitionCounts(ac); Map<ActivityId, ActivityPlan> activityPlanMap = buildActivityPlanMap(ac, jobRun, pcMap); assignConnectorPolicy(ac, activityPlanMap); TaskCluster[] taskClusters = computeTaskClusters(ac, jobRun, activityPlanMap); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Plan for " + ac); LOGGER.info("Built " + taskClusters.length + " Task Clusters"); for (TaskCluster tc : taskClusters) { LOGGER.info("Tasks: " + Arrays.toString(tc.getTasks())); } } return new ActivityClusterPlan(taskClusters, activityPlanMap); } private Map<ActivityId, ActivityPlan> buildActivityPlanMap(ActivityCluster ac, JobRun jobRun, Map<ActivityId, ActivityPartitionDetails> pcMap) { Map<ActivityId, ActivityPlan> activityPlanMap = new HashMap<ActivityId, ActivityPlan>(); Set<ActivityId> depAnIds = new HashSet<ActivityId>(); for (ActivityId anId : ac.getActivityMap().keySet()) { depAnIds.clear(); getDependencyActivityIds(depAnIds, anId, ac); ActivityPartitionDetails apd = pcMap.get(anId); Task[] tasks = new Task[apd.getPartitionCount()]; ActivityPlan activityPlan = new ActivityPlan(apd); for (int i = 0; i < tasks.length; ++i) { TaskId tid = new TaskId(anId, i); tasks[i] = new Task(tid, activityPlan); for (ActivityId danId : depAnIds) { ActivityCluster dAC = ac.getActivityClusterGraph().getActivityMap().get(danId); ActivityClusterPlan dACP = jobRun.getActivityClusterPlanMap().get(dAC.getId()); assert dACP != null : "IllegalStateEncountered: Dependent AC is being planned without a plan for dependency AC: Encountered no plan for ActivityID " + danId; Task[] dATasks = dACP.getActivityPlanMap().get(danId).getTasks(); assert dATasks != null : "IllegalStateEncountered: Dependent AC is being planned without a plan for dependency AC: Encountered no plan for ActivityID " + danId; assert dATasks.length == tasks.length : "Dependency activity partitioned differently from dependent: " + dATasks.length + " != " + tasks.length; Task dTask = dATasks[i]; TaskId dTaskId = dTask.getTaskId(); tasks[i].getDependencies().add(dTaskId); dTask.getDependents().add(tid); } } activityPlan.setTasks(tasks); activityPlanMap.put(anId, activityPlan); } return activityPlanMap; } private TaskCluster[] computeTaskClusters(ActivityCluster ac, JobRun jobRun, Map<ActivityId, ActivityPlan> activityPlanMap) { Set<ActivityId> activities = ac.getActivityMap().keySet(); Map<TaskId, List<Pair<TaskId, ConnectorDescriptorId>>> taskConnectivity = computeTaskConnectivity(jobRun, activityPlanMap, activities); TaskCluster[] taskClusters = ac.getActivityClusterGraph().isUseConnectorPolicyForScheduling() ? buildConnectorPolicyAwareTaskClusters( ac, activityPlanMap, taskConnectivity) : buildConnectorPolicyUnawareTaskClusters(ac, activityPlanMap); for (TaskCluster tc : taskClusters) { Set<TaskCluster> tcDependencyTaskClusters = tc.getDependencyTaskClusters(); for (Task ts : tc.getTasks()) { TaskId tid = ts.getTaskId(); List<Pair<TaskId, ConnectorDescriptorId>> cInfoList = taskConnectivity.get(tid); if (cInfoList != null) { for (Pair<TaskId, ConnectorDescriptorId> p : cInfoList) { Task targetTS = activityPlanMap.get(p.getLeft().getActivityId()).getTasks()[p.getLeft() .getPartition()]; TaskCluster targetTC = targetTS.getTaskCluster(); if (targetTC != tc) { ConnectorDescriptorId cdId = p.getRight(); PartitionId pid = new PartitionId(jobRun.getJobId(), cdId, tid.getPartition(), p.getLeft() .getPartition()); tc.getProducedPartitions().add(pid); targetTC.getRequiredPartitions().add(pid); partitionProducingTaskClusterMap.put(pid, tc); } } } for (TaskId dTid : ts.getDependencies()) { TaskCluster dTC = getTaskCluster(dTid); dTC.getDependentTaskClusters().add(tc); tcDependencyTaskClusters.add(dTC); } } } return taskClusters; } private TaskCluster[] buildConnectorPolicyUnawareTaskClusters(ActivityCluster ac, Map<ActivityId, ActivityPlan> activityPlanMap) { List<Task> taskStates = new ArrayList<Task>(); for (ActivityId anId : ac.getActivityMap().keySet()) { ActivityPlan ap = activityPlanMap.get(anId); Task[] tasks = ap.getTasks(); for (Task t : tasks) { taskStates.add(t); } } TaskCluster tc = new TaskCluster(new TaskClusterId(ac.getId(), 0), ac, taskStates.toArray(new Task[taskStates .size()])); for (Task t : tc.getTasks()) { t.setTaskCluster(tc); } return new TaskCluster[] { tc }; } private Map<TaskId, List<Pair<TaskId, ConnectorDescriptorId>>> computeTaskConnectivity(JobRun jobRun, Map<ActivityId, ActivityPlan> activityPlanMap, Set<ActivityId> activities) { Map<TaskId, List<Pair<TaskId, ConnectorDescriptorId>>> taskConnectivity = new HashMap<TaskId, List<Pair<TaskId, ConnectorDescriptorId>>>(); ActivityClusterGraph acg = jobRun.getActivityClusterGraph(); BitSet targetBitmap = new BitSet(); for (ActivityId ac1 : activities) { ActivityCluster ac = acg.getActivityMap().get(ac1); Task[] ac1TaskStates = activityPlanMap.get(ac1).getTasks(); int nProducers = ac1TaskStates.length; List<IConnectorDescriptor> outputConns = ac.getActivityOutputMap().get(ac1); if (outputConns != null) { for (IConnectorDescriptor c : outputConns) { ConnectorDescriptorId cdId = c.getConnectorId(); ActivityId ac2 = ac.getConsumerActivity(cdId); Task[] ac2TaskStates = activityPlanMap.get(ac2).getTasks(); int nConsumers = ac2TaskStates.length; if (c.allProducersToAllConsumers()) { List<Pair<TaskId, ConnectorDescriptorId>> cInfoList = new ArrayList<Pair<TaskId, ConnectorDescriptorId>>(); for (int j = 0; j < nConsumers; j++) { TaskId targetTID = ac2TaskStates[j].getTaskId(); cInfoList.add(Pair.<TaskId, ConnectorDescriptorId> of(targetTID, cdId)); } for (int i = 0; i < nProducers; ++i) { taskConnectivity.put(ac1TaskStates[i].getTaskId(), cInfoList); } } else { for (int i = 0; i < nProducers; ++i) { c.indicateTargetPartitions(nProducers, nConsumers, i, targetBitmap); List<Pair<TaskId, ConnectorDescriptorId>> cInfoList = taskConnectivity.get(ac1TaskStates[i] .getTaskId()); if (cInfoList == null) { cInfoList = new ArrayList<Pair<TaskId, ConnectorDescriptorId>>(); taskConnectivity.put(ac1TaskStates[i].getTaskId(), cInfoList); } for (int j = targetBitmap.nextSetBit(0); j >= 0; j = targetBitmap.nextSetBit(j + 1)) { TaskId targetTID = ac2TaskStates[j].getTaskId(); cInfoList.add(Pair.<TaskId, ConnectorDescriptorId> of(targetTID, cdId)); } } } } } } return taskConnectivity; } private TaskCluster[] buildConnectorPolicyAwareTaskClusters(ActivityCluster ac, Map<ActivityId, ActivityPlan> activityPlanMap, Map<TaskId, List<Pair<TaskId, ConnectorDescriptorId>>> taskConnectivity) { Map<TaskId, Set<TaskId>> taskClusterMap = new HashMap<TaskId, Set<TaskId>>(); for (ActivityId anId : ac.getActivityMap().keySet()) { ActivityPlan ap = activityPlanMap.get(anId); Task[] tasks = ap.getTasks(); for (Task t : tasks) { Set<TaskId> cluster = new HashSet<TaskId>(); TaskId tid = t.getTaskId(); cluster.add(tid); taskClusterMap.put(tid, cluster); } } JobRun jobRun = scheduler.getJobRun(); Map<ConnectorDescriptorId, IConnectorPolicy> connectorPolicies = jobRun.getConnectorPolicyMap(); for (Map.Entry<TaskId, List<Pair<TaskId, ConnectorDescriptorId>>> e : taskConnectivity.entrySet()) { Set<TaskId> cluster = taskClusterMap.get(e.getKey()); for (Pair<TaskId, ConnectorDescriptorId> p : e.getValue()) { IConnectorPolicy cPolicy = connectorPolicies.get(p.getRight()); if (cPolicy.requiresProducerConsumerCoscheduling()) { cluster.add(p.getLeft()); } } } /* * taskClusterMap contains for every TID x, x -> { coscheduled consumer TIDs U x } * We compute the transitive closure of this relation to find the largest set of * tasks that need to be co-scheduled */ int counter = 0; TaskId[] ordinalList = new TaskId[taskClusterMap.size()]; Map<TaskId, Integer> ordinalMap = new HashMap<TaskId, Integer>(); for (TaskId tid : taskClusterMap.keySet()) { ordinalList[counter] = tid; ordinalMap.put(tid, counter); ++counter; } int n = ordinalList.length; BitSet[] paths = new BitSet[n]; for (Map.Entry<TaskId, Set<TaskId>> e : taskClusterMap.entrySet()) { int i = ordinalMap.get(e.getKey()); BitSet bsi = paths[i]; if (bsi == null) { bsi = new BitSet(n); paths[i] = bsi; } for (TaskId ttid : e.getValue()) { int j = ordinalMap.get(ttid); paths[i].set(j); BitSet bsj = paths[j]; if (bsj == null) { bsj = new BitSet(n); paths[j] = bsj; } bsj.set(i); } } for (int k = 0; k < n; ++k) { for (int i = paths[k].nextSetBit(0); i >= 0; i = paths[k].nextSetBit(i + 1)) { for (int j = paths[i].nextClearBit(0); j < n && j >= 0; j = paths[i].nextClearBit(j + 1)) { paths[i].set(j, paths[k].get(j)); paths[j].set(i, paths[i].get(j)); } } } BitSet pending = new BitSet(n); pending.set(0, n); List<List<TaskId>> clusters = new ArrayList<List<TaskId>>(); for (int i = pending.nextSetBit(0); i >= 0; i = pending.nextSetBit(i)) { List<TaskId> cluster = new ArrayList<TaskId>(); for (int j = paths[i].nextSetBit(0); j >= 0; j = paths[i].nextSetBit(j + 1)) { cluster.add(ordinalList[j]); pending.clear(j); } clusters.add(cluster); } List<TaskCluster> tcSet = new ArrayList<TaskCluster>(); counter = 0; for (List<TaskId> cluster : clusters) { List<Task> taskStates = new ArrayList<Task>(); for (TaskId tid : cluster) { taskStates.add(activityPlanMap.get(tid.getActivityId()).getTasks()[tid.getPartition()]); } TaskCluster tc = new TaskCluster(new TaskClusterId(ac.getId(), counter++), ac, taskStates.toArray(new Task[taskStates.size()])); tcSet.add(tc); for (TaskId tid : cluster) { activityPlanMap.get(tid.getActivityId()).getTasks()[tid.getPartition()].setTaskCluster(tc); } } TaskCluster[] taskClusters = tcSet.toArray(new TaskCluster[tcSet.size()]); return taskClusters; } private TaskCluster getTaskCluster(TaskId tid) { JobRun run = scheduler.getJobRun(); ActivityCluster ac = run.getActivityClusterGraph().getActivityMap().get(tid.getActivityId()); ActivityClusterPlan acp = run.getActivityClusterPlanMap().get(ac.getId()); Task[] tasks = acp.getActivityPlanMap().get(tid.getActivityId()).getTasks(); Task task = tasks[tid.getPartition()]; assert task.getTaskId().equals(tid); return task.getTaskCluster(); } private void getDependencyActivityIds(Set<ActivityId> depAnIds, ActivityId anId, ActivityCluster ac) { Set<ActivityId> blockers = ac.getBlocked2BlockerMap().get(anId); if (blockers != null) { depAnIds.addAll(blockers); } } private void assignConnectorPolicy(ActivityCluster ac, Map<ActivityId, ActivityPlan> taskMap) { Map<ConnectorDescriptorId, IConnectorPolicy> cPolicyMap = new HashMap<ConnectorDescriptorId, IConnectorPolicy>(); Set<ActivityId> activities = ac.getActivityMap().keySet(); BitSet targetBitmap = new BitSet(); for (ActivityId a1 : activities) { Task[] ac1TaskStates = taskMap.get(a1).getTasks(); int nProducers = ac1TaskStates.length; List<IConnectorDescriptor> outputConns = ac.getActivityOutputMap().get(a1); if (outputConns != null) { for (IConnectorDescriptor c : outputConns) { ConnectorDescriptorId cdId = c.getConnectorId(); ActivityId a2 = ac.getConsumerActivity(cdId); Task[] ac2TaskStates = taskMap.get(a2).getTasks(); int nConsumers = ac2TaskStates.length; int[] fanouts = new int[nProducers]; if (c.allProducersToAllConsumers()) { for (int i = 0; i < nProducers; ++i) { fanouts[i] = nConsumers; } } else { for (int i = 0; i < nProducers; ++i) { c.indicateTargetPartitions(nProducers, nConsumers, i, targetBitmap); fanouts[i] = targetBitmap.cardinality(); } } IConnectorPolicy cp = assignConnectorPolicy(ac, c, nProducers, nConsumers, fanouts); cPolicyMap.put(cdId, cp); } } } scheduler.getJobRun().getConnectorPolicyMap().putAll(cPolicyMap); } private IConnectorPolicy assignConnectorPolicy(ActivityCluster ac, IConnectorDescriptor c, int nProducers, int nConsumers, int[] fanouts) { IConnectorPolicyAssignmentPolicy cpap = ac.getConnectorPolicyAssignmentPolicy(); if (cpap != null) { return cpap.getConnectorPolicyAssignment(c, nProducers, nConsumers, fanouts); } cpap = ac.getActivityClusterGraph().getConnectorPolicyAssignmentPolicy(); if (cpap != null) { return cpap.getConnectorPolicyAssignment(c, nProducers, nConsumers, fanouts); } return new PipeliningConnectorPolicy(); } private Map<ActivityId, ActivityPartitionDetails> computePartitionCounts(ActivityCluster ac) throws HyracksException { PartitionConstraintSolver solver = scheduler.getSolver(); Set<LValueConstraintExpression> lValues = new HashSet<LValueConstraintExpression>(); for (ActivityId anId : ac.getActivityMap().keySet()) { lValues.add(new PartitionCountExpression(anId.getOperatorDescriptorId())); } solver.solve(lValues); Map<OperatorDescriptorId, Integer> nPartMap = new HashMap<OperatorDescriptorId, Integer>(); for (LValueConstraintExpression lv : lValues) { Object value = solver.getValue(lv); if (value == null) { throw new HyracksException("No value found for " + lv); } if (!(value instanceof Number)) { throw new HyracksException("Unexpected type of value bound to " + lv + ": " + value.getClass() + "(" + value + ")"); } int nParts = ((Number) value).intValue(); if (nParts <= 0) { throw new HyracksException("Unsatisfiable number of partitions for " + lv + ": " + nParts); } nPartMap.put(((PartitionCountExpression) lv).getOperatorDescriptorId(), Integer.valueOf(nParts)); } Map<ActivityId, ActivityPartitionDetails> activityPartsMap = new HashMap<ActivityId, ActivityPartitionDetails>(); for (ActivityId anId : ac.getActivityMap().keySet()) { int nParts = nPartMap.get(anId.getOperatorDescriptorId()); int[] nInputPartitions = null; List<IConnectorDescriptor> inputs = ac.getActivityInputMap().get(anId); if (inputs != null) { nInputPartitions = new int[inputs.size()]; for (int i = 0; i < nInputPartitions.length; ++i) { ConnectorDescriptorId cdId = inputs.get(i).getConnectorId(); ActivityId aid = ac.getProducerActivity(cdId); Integer nPartInt = nPartMap.get(aid.getOperatorDescriptorId()); nInputPartitions[i] = nPartInt; } } int[] nOutputPartitions = null; List<IConnectorDescriptor> outputs = ac.getActivityOutputMap().get(anId); if (outputs != null) { nOutputPartitions = new int[outputs.size()]; for (int i = 0; i < nOutputPartitions.length; ++i) { ConnectorDescriptorId cdId = outputs.get(i).getConnectorId(); ActivityId aid = ac.getConsumerActivity(cdId); Integer nPartInt = nPartMap.get(aid.getOperatorDescriptorId()); nOutputPartitions[i] = nPartInt; } } ActivityPartitionDetails apd = new ActivityPartitionDetails(nParts, nInputPartitions, nOutputPartitions); activityPartsMap.put(anId, apd); } return activityPartsMap; } public Map<? extends PartitionId, ? extends TaskCluster> getPartitionProducingTaskClusterMap() { return partitionProducingTaskClusterMap; } }
/** * */ package li.moskito.awtt.protocol; import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicBoolean; import li.moskito.awtt.protocol.http.HttpProtocolException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A channel to read or write messages. * * @author Gerald */ public abstract class MessageChannel implements ByteChannel { /** * SLF4J Logger for this class */ private static final Logger LOG = LoggerFactory.getLogger(MessageChannel.class); /** * The queue in which messages are kept for being written to ByteBuffer upon invocation of the read method. */ private final Queue<Message> outMessageQueue; /** * The queue in which messages are kept from being read from a ByteBuffer upon invocation of the write method. */ private final Queue<Message> inMessageQueue; /** * The last partialWrittenMessage */ private Message partialWrittenMessage; /** * The last partialReadMessage */ private Message partialReadMessage; /** * Flag to indicate whether the channel is still open */ private final AtomicBoolean open; /** * Options map for configuration of the channel */ private final Map<MessageChannelOption<?>, Object> options; private final Map<Event.Type, Set<ChannelEventListener>> eventSubscriptions; /** * Mode to be used for writing or reading. * * @author Gerald */ protected static enum Mode { /** * A Read or Write operation should be performed from the beginning */ BEGIN, /** * A previously started read or write operation should be continued. The message passed was processed partially. */ CONTINUE; } /** * Events with no payload that are fired during the lifecycle of the channel. * * @author Gerald */ public enum LifecycleEvents implements Event<Object>, Event.Type { OUTPUT_QUEUE_EMPTY, ; @Override public Object getEventData() { return null; } @Override public Event.Type getType() { return this; } } /** * Standard event type * * @author Gerald */ public enum ErrorEvents implements Event.Type { PARSE_ERROR, ; } /** * */ public MessageChannel() { this.open = new AtomicBoolean(true); this.outMessageQueue = new ConcurrentLinkedQueue<>(); this.inMessageQueue = new ConcurrentLinkedQueue<>(); this.options = new ConcurrentHashMap<>(); this.eventSubscriptions = new ConcurrentHashMap<>(); } @Override public int read(final ByteBuffer byteBuffer) throws IOException { if (!this.open.get()) { throw new IOException("MessageChannel already closed"); } final Message message; final Mode mode; if (this.partialWrittenMessage != null) { message = this.partialWrittenMessage; this.partialWrittenMessage = null; mode = Mode.CONTINUE; } else if (this.outMessageQueue.peek() != null) { message = this.outMessageQueue.remove(); mode = Mode.BEGIN; } else { this.fireEvent(LifecycleEvents.OUTPUT_QUEUE_EMPTY); return -1; } final int dataLength = this.writeMessageToBuffer(message, byteBuffer, mode); if (dataLength != -1) { this.suspendWriteToBuffer(message); } else if (this.outMessageQueue.isEmpty()) { this.fireEvent(LifecycleEvents.OUTPUT_QUEUE_EMPTY); } return dataLength; } @Override public int write(final ByteBuffer byteBuffer) throws IOException { if (!this.open.get()) { throw new IOException("MessageChannel already closed"); } final Mode mode; if (this.partialReadMessage != null) { mode = Mode.CONTINUE; } else if (byteBuffer.hasRemaining()) { mode = Mode.BEGIN; } else { return -1; } return this.readMessageFromBuffer(byteBuffer, mode); } @Override public boolean isOpen() { return this.open.get(); } @Override public void close() throws IOException { this.open.set(false); } /** * Processes all read messages and by this creates response message that can be read. The processing of the input * messages is delegated to the {@link Protocol} and its process method. * * @return this channel */ public MessageChannel processMessages() { final Protocol protocol = this.getProtocol(); while (this.hasMessage()) { final Message response = protocol.process(this.readMessage()); if (response != null) { this.write(response); } } return this; } /** * Sets an option on the channel. * * @param option * the option to set * @param value * @throws IllegalArgumentException * if the option is either not supported by the channel or the value is not compatible with the type of * the option */ public void setOption(final MessageChannelOption<?> option, final Object value) { if (!this.getSupportedOptions().contains(option)) { throw new IllegalArgumentException("Option " + option + " is not supported"); } if (!option.type().isAssignableFrom(value.getClass())) { throw new IllegalArgumentException("Option value " + value + " is not of type " + option.type()); } this.options.put(option, value); } /** * Returns the value of the specified option * * @param option * the option for which the value should be returned * @return the value if the option is set of the default value for the option */ @SuppressWarnings("unchecked") public <T> T getOption(final MessageChannelOption<T> option) { if (this.options.containsKey(option)) { return (T) this.options.get(option); } return option.getDefault(); } /** * Returns a set of the options supported by this channel. * * @return */ @SuppressWarnings("rawtypes") public abstract Set<MessageChannelOption> getSupportedOptions(); /** * The {@link Protocol} for this message channel. * * @return */ protected abstract Protocol getProtocol(); /** * Checks if there are messages in the input queue that were read from buffer. Prior to this call a message as bytes * has to be written to the channel using the write(ByteBuffer) method. using the write method * * @return <code>true</code> if there are messages available */ public boolean hasMessage() { return this.inMessageQueue.peek() != null; } /** * Reads the next message from the input queue. Prior to this call a Message has to be written to the channel using * the write method. * * @return the next message from the queue or <code>null</code> if no message is in the queue */ public Message readMessage() { return this.inMessageQueue.poll(); } /** * Puts a message on the output queue. The next read operation will trigger the serialization of the message to a * {@link ByteBuffer} * * @param message * the message to be written to the channel */ public MessageChannel write(final Message message) { this.outMessageQueue.offer(message); return this; } /** * @return <code>true</code> when the previous write operation has not been completely fulfilled */ public boolean hasPartiallyReadMessage() { return this.partialReadMessage != null; } /** * @return <code>true</code> when the previous read operation has not been completely fulfilled */ public boolean hasPartiallyWrittenMessage() { return this.partialWrittenMessage != null; } /** * Suspends the read processes and puts the partially read message on hold. Upon the next write call the message * will be resumed. * * @param partialReadMessage * the message that has been partially read from the input buffer. */ protected void suspendReadFromBuffer(final Message partialReadMessage) { this.partialReadMessage = partialReadMessage; } /** * Suspends the write processes and puts the partially written message on hold. Upon the next read call the message * will be resumed and transferred to the target buffer. * * @param partialWrittenMessage * message that has been partially written to the buffer. */ protected void suspendWriteToBuffer(final Message partialWrittenMessage) { this.partialWrittenMessage = partialWrittenMessage; } /** * Discards the last partially written message. The message will be lost. * * @return the partial message. */ protected Message discardPartiallyReadMessage() { final Message partialMessage = this.partialReadMessage; this.partialReadMessage = null; return partialMessage; } /** * Discards the last partially read message. The message will be lost. * * @return the partial message. */ protected <T extends Message> T discardPartiallyWrittenMessage() { @SuppressWarnings("unchecked") final T partialMessage = (T) this.partialWrittenMessage; this.partialWrittenMessage = null; return partialMessage; } /** * Reads and parses a message from the given buffer and notifies the callback once the message has been read. * * @param byteBuffer * the bytebuffer to write the serialized message to * @param newMessageCallback * the callback that should be invoked when the parsing of a new message has been completed. * @param mode * the mode in which the operation should be performed. See {@link Mode}. If the mode is CONTINUE the * implementor should check if the are partiallyReadMessages() and continue the parsing of the message. * The message can be obtained by the discardPartiallyReadMessage() * @return the number of bytes written to the buffer */ private int readMessageFromBuffer(final ByteBuffer src, final Mode mode) throws IOException { switch (mode) { case BEGIN: return this.readMessage(src); case CONTINUE: break; default: break; } return 0; } /** * Reads a message from the byte buffer. Upon finishing the read operation the callback is notified that a message * has been read. <br> * The method does not support reading of large data (yet). * * @param src * the src buffer from which to read the data * @param callback * the callback that is notified when a message has been read * @return the number of bytes read or -1 if the entire data has been read * @throws IOException */ private int readMessage(final ByteBuffer src) throws IOException { final int dataLength = src.limit(); try { final Message message = this.parseMessage(src); this.receiveIncomingMessage(message); } catch (final ProtocolException e) { LOG.warn("Could not parse request", e); if (this.hasSubscribers(ErrorEvents.PARSE_ERROR)) { this.fireEvent(new BaseEvent<ProtocolException>(ErrorEvents.PARSE_ERROR, e)); } } return src.hasRemaining() ? dataLength : -1; } /** * Puts a message into the input queue. * * @param message */ protected void receiveIncomingMessage(final Message message) { this.inMessageQueue.offer(message); } /** * Writes a message to the buffer. * * @param message * the message to be written to the buffer * @param byteBuffer * the bytebuffer to write the serialized message to * @param mode * the mode in which the operation should be performed. See {@link Mode} * @return the number of bytes written to the buffer */ private int writeMessageToBuffer(final Message message, final ByteBuffer dst, final Mode mode) throws IOException { switch (mode) { case BEGIN: return this.writeMessage(message, dst); case CONTINUE: return this.writeBody(message.getBody(), dst); default: break; } return 0; } /** * Writes the given message to the destination buffer. The method first writes the header of the message. The buffer * must be capable of taking the entire header, otherwise a {@link BufferUnderflowException} will occur. If the body * of the message is larger than the space left (remaining) in the buffer, it is written partially and continued * upon the next invocation of read (see superclass). <br> * The default implementation writes the header of the message completely and streams the content of an optional * {@link BinaryBody}. * * @param message * the message to be sent * @param dst * the destination buffer for the data to be sent * @return the data written or -1 if all data has been written * @throws IOException */ protected int writeMessage(final Message message, final ByteBuffer dst) throws IOException { final int headerLength = this.writeHeader(message.getHeader(), dst, message.getCharset()); final int bodyLength = this.writeBody(message.getBody(), dst); final int dataLength; if (bodyLength != -1) { dataLength = headerLength + bodyLength; } else { dataLength = -1; } return dataLength; } /** * Writes the remaining data of the channel into the buffer. If there is more data available than remaining space in * the buffer, the number of bytes written is returned. If the channel reached its end -1 is returned.<br> * The default implementation only writes bodies of type {@link BinaryBody}. Override this method for writing custom * body types. * * @param partialResponse * the partial response whose body should be written * @param dst * the destination buffer to write the data to * @return the number of bytes written to the buffer or -1 if the channel of the body reached its end. * @throws IOException */ protected int writeBody(final Body body, final ByteBuffer dst) throws IOException { if (body instanceof BinaryBody) { final ReadableByteChannel ch = ((BinaryBody) body).getByteChannel(); if (ch != null) { final int dataLength = ch.read(dst); LOG.debug("Body written, {} Bytes", dataLength == -1 ? "until EOF" : dataLength); if (dataLength == -1) { ch.close(); } return dataLength; } } return -1; } /** * Writes the header to the dst buffer. The buffer is supposed to accept the entire header, otherwise a * {@link BufferUnderflowException} occurs. * * @param header * the header to be written * @param dst * the destination of the write operation * @param charset * @return the number of bytes written to the buffer (aka the header length) */ protected int writeHeader(final Header header, final ByteBuffer dst, final Charset charset) { final ByteBuffer buf = charset.encode(this.serializeHeader(header)); final int headerLength = buf.limit(); // write the header dst.put(buf); LOG.debug("Header written, {} Bytes", headerLength); return headerLength; } /** * Method to check if there are subscribers for a specific event type. If there are no subscribers, the creation of * an event can and should be skipped. * * @param type * type to verify * @return <code>true</code> if there are subscribers to the specified event type */ protected boolean hasSubscribers(final Event.Type type) { return this.eventSubscriptions.containsKey(type); } /** * Event method that is invoked when the output queue is empty and all messages have been transmitted. Default * implementation is empty. Override this method to react on events. */ protected void fireEvent(final Event<?> event) { if (this.eventSubscriptions.containsKey(event.getType())) { final Set<ChannelEventListener> listeners = this.eventSubscriptions.get(event.getType()); for (final ChannelEventListener listener : listeners) { listener.onEvent(event); } } } /** * Creates a subscription for the specified event type. The specified listener will be notified once an event of the * specified type occurred. * * @param type * the type to subscribe to * @param listener * the listener to be notified */ public void subscribe(final Event.Type type, final ChannelEventListener listener) { if (!this.eventSubscriptions.containsKey(type)) { this.eventSubscriptions.put(type, new CopyOnWriteArraySet<ChannelEventListener>()); } this.eventSubscriptions.get(type).add(listener); } /** * Parses an entire request from the given byteBuffer. * * @param src * the buffer containing the data that should be parsed * @return the parsed message * @throws ProtocolException * if the buffer contained data that were not parseable by the underlying protocol * @throws IOException * @throws HttpProtocolException */ protected abstract Message parseMessage(ByteBuffer src) throws ProtocolException, IOException; /** * Serializes a response into a CharBuffer. * * @param httpResponse * the response to be serialized * @return a CharBuffer containing the response in character representation */ protected abstract CharBuffer serializeHeader(Header header); }
package com.geektime.rnonesignalandroid; import java.util.Collection; import java.util.Iterator; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.content.pm.ApplicationInfo; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.LifecycleEventListener; 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.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.bridge.Promise; import com.onesignal.OSInAppMessageAction; import com.onesignal.OSPermissionState; import com.onesignal.OSPermissionSubscriptionState; import com.onesignal.OSSubscriptionState; import com.onesignal.OSEmailSubscriptionState; import com.onesignal.OneSignal; import com.onesignal.OneSignal.EmailUpdateHandler; import com.onesignal.OneSignal.EmailUpdateError; import com.onesignal.OneSignal.InAppMessageClickHandler; import com.onesignal.OneSignal.NotificationOpenedHandler; import com.onesignal.OneSignal.NotificationReceivedHandler; import com.onesignal.OSNotificationOpenResult; import com.onesignal.OSNotification; import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException; /** * Created by Avishay on 1/31/16. */ public class RNOneSignal extends ReactContextBaseJavaModule implements LifecycleEventListener, NotificationReceivedHandler, NotificationOpenedHandler, InAppMessageClickHandler { public static final String HIDDEN_MESSAGE_KEY = "hidden"; private ReactApplicationContext mReactApplicationContext; private ReactContext mReactContext; private boolean oneSignalInitDone; private boolean registeredEvents = false; private OSNotificationOpenResult coldStartNotificationResult; private OSInAppMessageAction inAppMessageActionResult; private boolean hasSetNotificationOpenedHandler = false; private boolean hasSetInAppClickedHandler = false; private boolean hasSetRequiresPrivacyConsent = false; private boolean waitingForUserPrivacyConsent = false; //ensure only one callback exists at a given time due to react-native restriction private Callback pendingGetTagsCallback; public RNOneSignal(ReactApplicationContext reactContext) { super(reactContext); mReactApplicationContext = reactContext; mReactContext = reactContext; mReactContext.addLifecycleEventListener(this); initOneSignal(); } private String appIdFromManifest(ReactApplicationContext context) { try { ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), context.getPackageManager().GET_META_DATA); Bundle bundle = ai.metaData; return bundle.getString("onesignal_app_id"); } catch (Throwable t) { t.printStackTrace(); return null; } } // Initialize OneSignal only once when an Activity is available. // React creates an instance of this class to late for OneSignal to get the current Activity // based on registerActivityLifecycleCallbacks it uses to listen for the first Activity. // However it seems it is also to soon to call getCurrentActivity() from the reactContext as well. // This will normally succeed when onHostResume fires instead. private void initOneSignal() { // Uncomment to debug init issues. // OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.ERROR); OneSignal.sdkType = "react"; String appId = appIdFromManifest(mReactApplicationContext); if (appId != null && appId.length() > 0) init(appId); } private void sendEvent(String eventName, Object params) { mReactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } private JSONObject jsonFromErrorMessageString(String errorMessage) throws JSONException { return new JSONObject().put("error", errorMessage); } @ReactMethod public void init(String appId) { Context context = mReactApplicationContext.getCurrentActivity(); if (oneSignalInitDone) { Log.e("onesignal", "Already initialized the OneSignal React-Native SDK"); return; } oneSignalInitDone = true; OneSignal.sdkType = "react"; if (context == null) { // in some cases, especially when react-native-navigation is installed, // the activity can be null, so we can initialize with the context instead context = mReactApplicationContext.getApplicationContext(); } OneSignal.getCurrentOrNewInitBuilder().setInAppMessageClickHandler(this); OneSignal.init(context, null, appId, this, this); if (this.hasSetRequiresPrivacyConsent) this.waitingForUserPrivacyConsent = true; } @ReactMethod public void sendTag(String key, String value) { OneSignal.sendTag(key, value); } @ReactMethod public void sendTags(ReadableMap tags) { OneSignal.sendTags(RNUtils.readableMapToJson(tags)); } @ReactMethod public void getTags(final Callback callback) { if (pendingGetTagsCallback == null) pendingGetTagsCallback = callback; OneSignal.getTags(new OneSignal.GetTagsHandler() { @Override public void tagsAvailable(JSONObject tags) { if (pendingGetTagsCallback != null) pendingGetTagsCallback.invoke(RNUtils.jsonToWritableMap(tags)); pendingGetTagsCallback = null; } }); } @ReactMethod public void setUnauthenticatedEmail(String email, final Callback callback) { OneSignal.setEmail(email, null, new OneSignal.EmailUpdateHandler() { @Override public void onSuccess() { callback.invoke(); } @Override public void onFailure(EmailUpdateError error) { try { callback.invoke(RNUtils.jsonToWritableMap(jsonFromErrorMessageString(error.getMessage()))); } catch (JSONException exception) { exception.printStackTrace(); } } }); } @ReactMethod public void setEmail(String email, String emailAuthToken, final Callback callback) { OneSignal.setEmail(email, emailAuthToken, new EmailUpdateHandler() { @Override public void onSuccess() { callback.invoke(); } @Override public void onFailure(EmailUpdateError error) { try { callback.invoke(RNUtils.jsonToWritableMap(jsonFromErrorMessageString(error.getMessage()))); } catch (JSONException exception) { exception.printStackTrace(); } } }); } @ReactMethod public void logoutEmail(final Callback callback) { OneSignal.logoutEmail(new EmailUpdateHandler() { @Override public void onSuccess() { callback.invoke(); } @Override public void onFailure(EmailUpdateError error) { try { callback.invoke(RNUtils.jsonToWritableMap(jsonFromErrorMessageString(error.getMessage()))); } catch (JSONException exception) { exception.printStackTrace(); } } }); } @ReactMethod public void idsAvailable() { OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() { public void idsAvailable(String userId, String registrationId) { final WritableMap params = Arguments.createMap(); params.putString("userId", userId); params.putString("pushToken", registrationId); sendEvent("OneSignal-idsAvailable", params); } }); } @ReactMethod public void getPermissionSubscriptionState(final Callback callback) { OSPermissionSubscriptionState state = OneSignal.getPermissionSubscriptionState(); if (state == null) return; OSPermissionState permissionState = state.getPermissionStatus(); OSSubscriptionState subscriptionState = state.getSubscriptionStatus(); OSEmailSubscriptionState emailSubscriptionState = state.getEmailSubscriptionStatus(); // Notifications enabled for app? (Android Settings) boolean notificationsEnabled = permissionState.getEnabled(); // User subscribed to OneSignal? (automatically toggles with notificationsEnabled) boolean subscriptionEnabled = subscriptionState.getSubscribed(); // User's original subscription preference (regardless of notificationsEnabled) boolean userSubscriptionEnabled = subscriptionState.getUserSubscriptionSetting(); try { JSONObject result = new JSONObject(); result.put("notificationsEnabled", notificationsEnabled) .put("subscriptionEnabled", subscriptionEnabled) .put("userSubscriptionEnabled", userSubscriptionEnabled) .put("pushToken", subscriptionState.getPushToken()) .put("userId", subscriptionState.getUserId()) .put("emailUserId", emailSubscriptionState.getEmailUserId()) .put("emailAddress", emailSubscriptionState.getEmailAddress()); Log.d("onesignal", "permission subscription state: " + result.toString()); callback.invoke(RNUtils.jsonToWritableMap(result)); } catch (JSONException e) { e.printStackTrace(); } } @ReactMethod public void inFocusDisplaying(int displayOption) { OneSignal.setInFocusDisplaying(displayOption); } @ReactMethod public void deleteTag(String key) { OneSignal.deleteTag(key); } @ReactMethod public void enableVibrate(Boolean enable) { OneSignal.enableVibrate(enable); } @ReactMethod public void enableSound(Boolean enable) { OneSignal.enableSound(enable); } @ReactMethod public void setSubscription(Boolean enable) { OneSignal.setSubscription(enable); } @ReactMethod public void promptLocation() { OneSignal.promptLocation(); } @ReactMethod public void syncHashedEmail(String email) { OneSignal.syncHashedEmail(email); } @ReactMethod public void setLogLevel(int logLevel, int visualLogLevel) { OneSignal.setLogLevel(logLevel, visualLogLevel); } @ReactMethod public void setLocationShared(Boolean shared) { OneSignal.setLocationShared(shared); } @ReactMethod public void postNotification(String contents, String data, String playerId, String otherParameters) { try { JSONObject postNotification = new JSONObject(); postNotification.put("contents", new JSONObject(contents)); if (playerId != null) { JSONArray playerIds = new JSONArray(); playerIds.put(playerId); postNotification.put("include_player_ids", playerIds); } if (data != null) { JSONObject additionalData = new JSONObject(); additionalData.put("p2p_notification", new JSONObject(data)); postNotification.put("data", additionalData); } if (otherParameters != null && !otherParameters.trim().isEmpty()) { JSONObject parametersJson = new JSONObject(otherParameters.trim()); Iterator<String> keys = parametersJson.keys(); while (keys.hasNext()) { String key = keys.next(); postNotification.put(key, parametersJson.get(key)); } if (parametersJson.has(HIDDEN_MESSAGE_KEY) && parametersJson.getBoolean(HIDDEN_MESSAGE_KEY)) { postNotification.getJSONObject("data").put(HIDDEN_MESSAGE_KEY, true); } } OneSignal.postNotification( postNotification, new OneSignal.PostNotificationResponseHandler() { @Override public void onSuccess(JSONObject response) { Log.i("OneSignal", "postNotification Success: " + response.toString()); } @Override public void onFailure(JSONObject response) { Log.e("OneSignal", "postNotification Failure: " + response.toString()); } } ); } catch (JSONException e) { e.printStackTrace(); } } @ReactMethod public void clearOneSignalNotifications() { OneSignal.clearOneSignalNotifications(); } @ReactMethod public void cancelNotification(int id) { OneSignal.cancelNotification(id); } @ReactMethod public void setRequiresUserPrivacyConsent(Boolean required) { OneSignal.setRequiresUserPrivacyConsent(required); } @ReactMethod public void provideUserConsent(Boolean granted) { OneSignal.provideUserConsent(granted); } @ReactMethod public void userProvidedPrivacyConsent(Promise promise) { promise.resolve(OneSignal.userProvidedPrivacyConsent()); } @ReactMethod public void setExternalUserId(String externalId) { OneSignal.setExternalUserId(externalId); } @ReactMethod public void removeExternalUserId() { OneSignal.removeExternalUserId(); } @ReactMethod public void initNotificationOpenedHandlerParams() { this.hasSetNotificationOpenedHandler = true; if (this.coldStartNotificationResult != null) { this.notificationOpened(this.coldStartNotificationResult); this.coldStartNotificationResult = null; } } @Override public void notificationReceived(OSNotification notification) { this.sendEvent("OneSignal-remoteNotificationReceived", RNUtils.jsonToWritableMap(notification.toJSONObject())); } @Override public void notificationOpened(OSNotificationOpenResult result) { if (!this.hasSetNotificationOpenedHandler) { this.coldStartNotificationResult = result; return; } this.sendEvent("OneSignal-remoteNotificationOpened", RNUtils.jsonToWritableMap(result.toJSONObject())); } @ReactMethod public void addTrigger(String key, Object object) { OneSignal.addTrigger(key, object); } @ReactMethod public void addTriggers(ReadableMap triggers) { OneSignal.addTriggers(triggers.toHashMap()); } @ReactMethod public void removeTriggerForKey(String key) { OneSignal.removeTriggerForKey(key); } @ReactMethod public void removeTriggersForKeys(ReadableArray keys) { OneSignal.removeTriggersForKeys(RNUtils.convertReableArrayIntoStringCollection(keys)); } @ReactMethod public void getTriggerValueForKey(String key, Promise promise) { promise.resolve(OneSignal.getTriggerValueForKey(key)); } @ReactMethod public void pauseInAppMessages(Boolean pause) { OneSignal.pauseInAppMessages(pause); } @ReactMethod public void initInAppMessageClickHandlerParams() { this.hasSetInAppClickedHandler = true; if (inAppMessageActionResult != null) { this.inAppMessageClicked(this.inAppMessageActionResult); this.inAppMessageActionResult = null; } } @Override public void inAppMessageClicked(OSInAppMessageAction result) { if (!this.hasSetInAppClickedHandler) { this.inAppMessageActionResult = result; return; } this.sendEvent("OneSignal-inAppMessageClicked", RNUtils.jsonToWritableMap(result.toJSONObject())); } @Override public String getName() { return "OneSignal"; } @Override public void onHostDestroy() { } @Override public void onHostPause() { } @Override public void onHostResume() { initOneSignal(); } }
package controllers.api; import java.util.Collection; import java.util.Set; import org.mapdb.Fun; import org.mapdb.Fun.Tuple2; import com.google.common.base.Function; import com.google.common.collect.Collections2; import models.transit.Route; import models.transit.Trip; import models.transit.TripPattern; import controllers.Base; import controllers.Application; import controllers.Secure; import controllers.Security; import datastore.VersionedDataStore; import datastore.AgencyTx; import datastore.GlobalTx; import play.mvc.Before; import play.mvc.Controller; import play.mvc.With; @With(Secure.class) public class RouteController extends Controller { @Before static void initSession() throws Throwable { if(!Security.isConnected() && !Application.checkOAuth(request, session)) Secure.login(); } public static void getRoute(String id, String agencyId) { if (agencyId == null) agencyId = session.get("agencyId"); if (agencyId == null) { badRequest(); return; } final AgencyTx tx = VersionedDataStore.getAgencyTx(agencyId); try { if (id != null) { if (!tx.routes.containsKey(id)) { tx.rollback(); badRequest(); return; } Route route = tx.routes.get(id); route.addDerivedInfo(tx); renderJSON(Base.toJson(route, false)); } else { Route[] ret = tx.routes.values().toArray(new Route[tx.routes.size()]); for (Route r : ret) { r.addDerivedInfo(tx); } String json = Base.toJson(ret, false); tx.rollback(); renderJSON(json); } } catch (Exception e) { tx.rollbackIfOpen(); e.printStackTrace(); badRequest(); } } public static void createRoute() { Route route; try { route = Base.mapper.readValue(params.get("body"), Route.class); GlobalTx gtx = VersionedDataStore.getGlobalTx(); if (!gtx.agencies.containsKey(route.agencyId)) { gtx.rollback(); badRequest(); return; } if (session.contains("agencyId") && !session.get("agencyId").equals(route.agencyId)) badRequest(); gtx.rollback(); AgencyTx tx = VersionedDataStore.getAgencyTx(route.agencyId); if (tx.routes.containsKey(route.id)) { tx.rollback(); badRequest(); return; } // check if gtfsRouteId is specified, if not create from DB id if(route.gtfsRouteId == null) { route.gtfsRouteId = "ROUTE_" + route.id; } tx.routes.put(route.id, route); tx.commit(); renderJSON(Base.toJson(route, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void updateRoute() { Route route; try { route = Base.mapper.readValue(params.get("body"), Route.class); AgencyTx tx = VersionedDataStore.getAgencyTx(route.agencyId); if (!tx.routes.containsKey(route.id)) { tx.rollback(); notFound(); return; } if (session.contains("agencyId") && !session.get("agencyId").equals(route.agencyId)) badRequest(); // check if gtfsRouteId is specified, if not create from DB id if(route.gtfsRouteId == null) { route.gtfsRouteId = "ROUTE_" + route.id; } tx.routes.put(route.id, route); tx.commit(); renderJSON(Base.toJson(route, false)); } catch (Exception e) { e.printStackTrace(); badRequest(); } } public static void deleteRoute(String id, String agencyId) { if (agencyId == null) agencyId = session.get("agencyId"); if(id == null || agencyId == null) badRequest(); AgencyTx tx = VersionedDataStore.getAgencyTx(agencyId); try { if (!tx.routes.containsKey(id)) { tx.rollback(); notFound(); return; } Route r = tx.routes.get(id); // delete affected trips Set<Tuple2<String, String>> affectedTrips = tx.tripsByRoute.subSet(new Tuple2(r.id, null), new Tuple2(r.id, Fun.HI)); for (Tuple2<String, String> trip : affectedTrips) { tx.trips.remove(trip.b); } // delete affected patterns // note that all the trips on the patterns will have already been deleted above Set<Tuple2<String, String>> affectedPatts = tx.tripPatternsByRoute.subSet(new Tuple2(r.id, null), new Tuple2(r.id, Fun.HI)); for (Tuple2<String, String> tp : affectedPatts) { tx.tripPatterns.remove(tp.b); } tx.routes.remove(id); tx.commit(); ok(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); error(e); } } /** merge route from into route into, for the given agency ID */ public static void mergeRoutes (String from, String into, String agencyId) { if (agencyId == null) agencyId = session.get("agencyId"); if (agencyId == null || from == null || into == null) badRequest(); final AgencyTx tx = VersionedDataStore.getAgencyTx(agencyId); try { // ensure the routes exist if (!tx.routes.containsKey(from) || !tx.routes.containsKey(into)) { tx.rollback(); badRequest(); } // get all the trip patterns for route from // note that we clone them here so we can later modify them Collection<TripPattern> tps = Collections2.transform( tx.tripPatternsByRoute.subSet(new Tuple2(from, null), new Tuple2(from, Fun.HI)), new Function<Tuple2<String, String>, TripPattern> () { @Override public TripPattern apply(Tuple2<String, String> input) { try { return tx.tripPatterns.get(input.b).clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } }); for (TripPattern tp : tps) { tp.routeId = into; tx.tripPatterns.put(tp.id, tp); } // now move all the trips Collection<Trip> ts = Collections2.transform( tx.tripsByRoute.subSet(new Tuple2(from, null), new Tuple2(from, Fun.HI)), new Function<Tuple2<String, String>, Trip> () { @Override public Trip apply(Tuple2<String, String> input) { try { return tx.trips.get(input.b).clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new RuntimeException(e); } } }); for (Trip t : ts) { t.routeId = into; tx.trips.put(t.id, t); } tx.routes.remove(from); tx.commit(); ok(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); error(e); } } }
package org.orienteer.core.component.command; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.event.Broadcast; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.GenericPanel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.ResourceModel; import org.orienteer.core.behavior.UpdateOnActionPerformedEventBehavior; import org.orienteer.core.behavior.UpdateOnDashboardDisplayModeChangeBehavior; import org.orienteer.core.component.BootstrapSize; import org.orienteer.core.component.BootstrapType; import org.orienteer.core.component.FAIcon; import org.orienteer.core.component.FAIconType; import org.orienteer.core.component.IBootstrapAware; import org.orienteer.core.component.ICommandsSupportComponent; import org.orienteer.core.event.ActionPerformedEvent; import ru.ydn.wicket.wicketorientdb.OrientDbWebSession; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.metadata.schema.OSchema; /** * Main class for all commands * * @param <T> the type of an entity to which this command can be applied */ public abstract class Command<T> extends GenericPanel<T> implements IBootstrapAware { private static final AttributeModifier DISABLED_LINK_BEHAVIOR = new AttributeModifier("disabled", AttributeModifier.VALUELESS_ATTRIBUTE_ADD) { @Override public boolean isEnabled(Component component) { return !component.isEnabledInHierarchy(); } }; private static final long serialVersionUID = 1L; private IModel<?> labelModel; private String icon; private AbstractLink link; private String btnCssClass; private BootstrapType bootstrapType = BootstrapType.PRIMARY; private BootstrapSize bootstrapSize = BootstrapSize.DEFAULT; /** * If true - activate on event {@link UpdateOnActionPerformedEventBehavior} UpdateAlwaysOnActionPerformedEventBehavior/UpdateChangingOnActionPerformedEventBehavior */ private boolean changingModel=false; /** * If true - activate on event {@link UpdateOnDashboardDisplayModeChangeBehavior} behavior */ private boolean changingDisplayMode=false; /** * Auto send notes for {@link UpdateOnActionPerformedEventBehavior}(s) */ private boolean autoNotify=true; @SuppressWarnings("unchecked") public Command(IModel<?> labelModel, ICommandsSupportComponent<T> component) { this(labelModel, component, component instanceof Component ? (IModel<T>)((Component)component).getDefaultModel() : null); } public Command(IModel<?> labelModel, ICommandsSupportComponent<T> component, IModel<T> model) { this(component.newCommandId(), labelModel, model); } public Command(String commandId, String labelKey) { this(commandId, labelKey, null); } public Command(String commandId, String labelKey, IModel<T> model) { this(commandId, new ResourceModel(labelKey), model); } public Command(String commandId, IModel<?> labelModel) { this(commandId, labelModel, null); } public Command(String commandId, IModel<?> labelModel, IModel<T> model) { super(commandId, model); this.labelModel = labelModel; onInstantiation(); } protected void onInstantiation() { } /** * We are initializing link in onInitialize() because of some links we need to know a structure */ @Override protected void onInitialize() { super.onInitialize(); link = newLink("command"); link.setOutputMarkupId(true); link.add(new AttributeAppender("class", new PropertyModel<String>(this, "btnCssClass"), " ")); link.add(new Label("label", labelModel).setRenderBodyOnly(true)); link.add(new FAIcon("icon", new PropertyModel<String>(this, "icon"))); link.add(DISABLED_LINK_BEHAVIOR); add(link); } @Override public Command<T> add(Behavior... behaviors) { super.add(behaviors); return this; } protected AbstractLink newLink(String id) { return new Link<Object>(id) { /** * */ private static final long serialVersionUID = 1L; @Override public void onClick() { Command.this.onClick(); trySendActionPerformed(); } }; } public String getIcon() { return icon; } public Command<T> setIcon(String icon) { this.icon = icon; return this; } public Command<T> setIcon(FAIconType type) { this.icon = type!=null?type.getCssClass():null; return this; } public AbstractLink getLink() { return link; } public IModel<?> getLabelModel() { return link!=null?link.get("label").getDefaultModel():labelModel; } public Command<T> setLabelModel(IModel<?> labelModel) { if(link!=null) link.get("label").setDefaultModel(labelModel); else this.labelModel = labelModel; return this; } public String getBtnCssClass() { if(btnCssClass!=null) return btnCssClass; else { BootstrapType type = getBootstrapType(); if(type==null) return null; StringBuilder sb = new StringBuilder(); sb.append("btn ").append(type.getBtnCssClass()); BootstrapSize size = getBootstrapSize(); if(size!=null) sb.append(' ').append(size.getBtnCssClass()); return sb.toString(); } } public void setBtnCssClass(String btnCssClass) { this.btnCssClass = btnCssClass; } @Override public Command<T> setBootstrapType(BootstrapType type) { this.bootstrapType = type; return this; } @Override public BootstrapType getBootstrapType() { return bootstrapType; } @Override public Command<T> setBootstrapSize(BootstrapSize size) { this.bootstrapSize = size; return this; } @Override public BootstrapSize getBootstrapSize() { return bootstrapSize; } public ODatabaseDocumentInternal getDatabaseDocumentInternal() { return OrientDbWebSession.get().getDatabaseDocumentInternal(); } public ODatabaseSession getDatabaseSession() { return OrientDbWebSession.get().getDatabaseSession(); } public OSchema getSchema() { return getDatabaseSession().getMetadata().getSchema(); } public boolean isChangingModel() { return changingModel; } public Command<T> setChandingModel(boolean changingModel) { this.changingModel = changingModel; return this; } public boolean isChangingDisplayMode() { return changingDisplayMode; } public Command<T> setChangingDisplayMode(boolean changingDisplayMode) { this.changingDisplayMode = changingDisplayMode; return this; } public boolean isAutoNotify() { return autoNotify; } public Command<T> setAutoNotify(boolean autoNotify) { this.autoNotify = autoNotify; return this; } /** * Send {@link ActionPerformedEvent} only of auto notify is enabled */ protected void trySendActionPerformed() { if(isAutoNotify()) sendActionPerformed(); } protected void sendActionPerformed() { send(this, Broadcast.BUBBLE, newActionPerformedEvent()); } protected ActionPerformedEvent<T> newActionPerformedEvent() { return new ActionPerformedEvent<T>(this); } public abstract void onClick(); }
/* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowledgement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgement may appear in the software itself, * if and wherever such third-party acknowledgements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.jrcs.diff; import java.util.*; /** * Implements a simple differencing algortithm.<p> * * @date $Date$ * @version $Revision$ * @author <a href="mailto:juanco@suigeneris.org">Juanco Anez</a> * * <p><b>Overview of Algorithm</b></p> * * <p><i>by <a * href='http://www.topmeadow.net/bwm'> bwm</a> * </p> * * <p>The algorithm is optimised for situations where the input sequences * have few repeated objects. If it is given input with many repeated * objects it will report sub-optimal changes. However, given appropriate * input, it is fast, and linear in memory usage.</p> * * <p>The algorithm consists of the following steps:</p> * <ul> * <li>compute an equivalence set for the input data</li> * <li>translate each element of the orginal * and revised input sequences to a member of the equivalence set * </li> * <li>match the the input sequences to determine the deltas, i.e. * the differences between the original and revised sequences.</li> * </ul> * * <p>The first step is to compute a an equivalence set for the input data. * The equivalence set is computed from objects that are in the original * input sequence</p> * <pre> * eq(x) = the index of the first occurence of x in the original sequence. * </pre> * * <p>With this equivalence function, the algorithm can compare integers rather * than strings, which is considerably more efficient.</p> * * <p>The second step is to compute the datastructure on which the * algorithm will operate. Having computed the equivalence function * in the previous step, we can compute two arrays where * indx[i] = eqs(orig[i]) and jndx[i] = eqs(rev[i]). The algorithm can * now operate on indx and jndx instead of orig and rev. Thus, comparisons * are then on O(int == int) instead of O(Object.equals(Object)). * </p> * * <p>The algorithm now matches indx and jndx. Whilst indx[i] == jndx[i] * it skips matching objects in the sequence. In seeking to match objects * in the input sequence it assumes that each object is likely to be unique. * It uses the known characteristics of the unique equivalence function. It can * tell from the eq value if this object appeared in the other sequence * at all. If it did not, there is no point in searching for a match.</p> * * <p>Recall that the eq function value is the index earliest occurrence in * the orig sequence. This information is used to search efficiently for * the next match. The algorithm is perfect when all input objects are * unique, but degrades when input objects are not unique. When input * objects are not unique an optimal match may not be found, but a * correct match will be.</p> * * <p>Having identified common matching objects in the orig and revised * sequences, the differences between them are easily computed. * </p> * * @see Delta * @see Revision * Modifications: * * 27/Apr/2003 bwm * Added some comments whilst trying to figure out the algorithm * * 03 May 2003 bwm * Created this implementation class by refactoring it out of the Diff * class to enable plug in difference algorithms * */ public class SimpleDiff implements DiffAlgorithm { static final int NOT_FOUND_i = -2; static final int NOT_FOUND_j = -1; static final int EOS = Integer.MAX_VALUE; public SimpleDiff() { } protected int scan(int[] ndx, int i, int target) { while (ndx[i] < target) { i++; } return i; } /** * Compute the difference between original and revised sequences. * * @param orig The original sequence. * @param rev The revised sequence to be compared with the original. * @return A Revision object describing the differences. * @throws DifferenciationFailedException if the diff could not be computed. */ public Revision diff(Object[] orig, Object[] rev) throws DifferentiationFailedException { // create map eqs, such that for each item in both orig and rev // eqs(item) = firstOccurrence(item, orig); Map eqs = buildEqSet(orig, rev); // create an array such that // indx[i] = NOT_FOUND_i if orig[i] is not in rev // indx[i] = firstOccurrence(orig[i], orig) int[] indx = buildIndex(eqs, orig, NOT_FOUND_i); // create an array such that // jndx[j] = NOT_FOUND_j if orig[j] is not in rev // jndx[j] = firstOccurrence(rev[j], orig) int[] jndx = buildIndex(eqs, rev, NOT_FOUND_j); // what in effect has been done is to build a unique hash // for each item that is in both orig and rev // and to label each item in orig and new with that hash value // or a marker that the item is not common to both. eqs = null; // let gc know we're done with this Revision deltas = new Revision(); //!!! new Revision() int i = 0; int j = 0; // skip matching // skip leading items that are equal // could be written // for (i=0; indx[i] != EOS && indx[i] == jndx[i]; i++); // j = i; for (; indx[i] != EOS && indx[i] == jndx[j]; i++, j++) { /* void */ } while (indx[i] != jndx[j]) { // only equal if both == EOS // they are different int ia = i; int ja = j; // size of this delta do { // look down rev for a match // stop at a match // or if the FO(rev[j]) > FO(orig[i]) // or at the end while (jndx[j] < 0 || jndx[j] < indx[i]) { j++; } // look down orig for a match // stop at a match // or if the FO(orig[i]) > FO(rev[j]) // or at the end while (indx[i] < 0 || indx[i] < jndx[j]) { i++; } // this doesn't do a compare each line with each other line // so it won't find all matching lines } while (indx[i] != jndx[j]); // on exit we have a match // they are equal, reverse any exedent matches // it is possible to overshoot, so count back matching items while (i > ia && j > ja && indx[i - 1] == jndx[j - 1]) { --i; --j; } deltas.addDelta(Delta.newDelta(new Chunk(orig, ia, i - ia), new Chunk(rev, ja, j - ja))); // skip matching for (; indx[i] != EOS && indx[i] == jndx[j]; i++, j++) { /* void */ } } return deltas; } /** * create a <code>Map</code> from each common item in orig and rev * to the index of its first occurrence in orig * * @param orig the original sequence of items * @param rev the revised sequence of items */ protected Map buildEqSet(Object[] orig, Object[] rev) { // construct a set of the objects that orig and rev have in common // first construct a set containing all the elements in orig Set items = new HashSet(Arrays.asList(orig)); // then remove all those not in rev items.retainAll(Arrays.asList(rev)); Map eqs = new HashMap(); for (int i = 0; i < orig.length; i++) { // if its a common item and hasn't been found before if (items.contains(orig[i])) { // add it to the map eqs.put(orig[i], Integer.valueOf(i)); // and make sure its not considered again items.remove(orig[i]); } } return eqs; } /** * build a an array such each a[i] = eqs([i]) or NF if eqs([i]) undefined * * @param eqs a mapping from Object to Integer * @param seq a sequence of objects * @param NF the not found marker */ protected int[] buildIndex(Map eqs, Object[] seq, int NF) { int[] result = new int[seq.length + 1]; for (int i = 0; i < seq.length; i++) { Integer value = (Integer) eqs.get(seq[i]); if (value == null || value.intValue() < 0) { result[i] = NF; } else { result[i] = value.intValue(); } } result[seq.length] = EOS; return result; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.util.List; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.common.scanner.ClassPathScanner; import org.apache.drill.common.scanner.persistence.ScanResult; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.ExecTest; import org.apache.drill.exec.client.DrillClient; import org.apache.drill.exec.exception.SchemaChangeException; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.memory.RootAllocatorFactory; import org.apache.drill.exec.proto.UserBitShared; import org.apache.drill.exec.proto.UserBitShared.QueryId; import org.apache.drill.exec.proto.UserBitShared.QueryResult.QueryState; import org.apache.drill.exec.proto.UserBitShared.QueryType; import org.apache.drill.exec.record.RecordBatchLoader; import org.apache.drill.exec.rpc.ConnectionThrottle; import org.apache.drill.exec.rpc.user.AwaitableUserResultsListener; import org.apache.drill.exec.rpc.user.QueryDataBatch; import org.apache.drill.exec.rpc.user.UserResultsListener; import org.apache.drill.exec.rpc.user.UserSession; import org.apache.drill.exec.server.Drillbit; import org.apache.drill.exec.server.DrillbitContext; import org.apache.drill.exec.server.RemoteServiceSet; import org.apache.drill.exec.store.StoragePluginRegistry; import org.apache.drill.exec.util.TestUtilities; import org.apache.drill.exec.util.VectorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.io.Files; import com.google.common.io.Resources; public class BaseTestQuery extends ExecTest { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BaseTestQuery.class); protected static final String TEMP_SCHEMA = "dfs_test.tmp"; private static final String ENABLE_FULL_CACHE = "drill.exec.test.use-full-cache"; private static final int MAX_WIDTH_PER_NODE = 2; @SuppressWarnings("serial") private static final Properties TEST_CONFIGURATIONS = new Properties() { { put(ExecConstants.SYS_STORE_PROVIDER_LOCAL_ENABLE_WRITE, "false"); put(ExecConstants.HTTP_ENABLE, "false"); } }; public final TestRule resetWatcher = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { try { resetClientAndBit(); } catch (Exception e1) { throw new RuntimeException("Failure while resetting client.", e1); } } }; protected static DrillClient client; protected static Drillbit[] bits; protected static RemoteServiceSet serviceSet; protected static DrillConfig config; protected static BufferAllocator allocator; /** * Number of Drillbits in test cluster. Default is 1. * * Tests can update the cluster size through {@link #updateTestCluster(int, DrillConfig)} */ private static int drillbitCount = 1; /** * Location of the dfs_test.tmp schema on local filesystem. */ private static String dfsTestTmpSchemaLocation; private int[] columnWidths = new int[] { 8 }; private static ScanResult classpathScan; @BeforeClass public static void setupDefaultTestCluster() throws Exception { config = DrillConfig.create(TEST_CONFIGURATIONS); classpathScan = ClassPathScanner.fromPrescan(config); openClient(); // turns on the verbose errors in tests // sever side stacktraces are added to the message before sending back to the client test("ALTER SESSION SET `exec.errors.verbose` = true"); } protected static void updateTestCluster(int newDrillbitCount, DrillConfig newConfig) { Preconditions.checkArgument(newDrillbitCount > 0, "Number of Drillbits must be at least one"); if (drillbitCount != newDrillbitCount || config != null) { // TODO: Currently we have to shutdown the existing Drillbit cluster before starting a new one with the given // Drillbit count. Revisit later to avoid stopping the cluster. try { closeClient(); drillbitCount = newDrillbitCount; if (newConfig != null) { // For next test class, updated DrillConfig will be replaced by default DrillConfig in BaseTestQuery as part // of the @BeforeClass method of test class. config = newConfig; } openClient(); } catch(Exception e) { throw new RuntimeException("Failure while updating the test Drillbit cluster.", e); } } } /** * Useful for tests that require a DrillbitContext to get/add storage plugins, options etc. * * @return DrillbitContext of first Drillbit in the cluster. */ protected static DrillbitContext getDrillbitContext() { Preconditions.checkState(bits != null && bits[0] != null, "Drillbits are not setup."); return bits[0].getContext(); } protected static Properties cloneDefaultTestConfigProperties() { final Properties props = new Properties(); for(String propName : TEST_CONFIGURATIONS.stringPropertyNames()) { props.put(propName, TEST_CONFIGURATIONS.getProperty(propName)); } return props; } protected static String getDfsTestTmpSchemaLocation() { return dfsTestTmpSchemaLocation; } private static void resetClientAndBit() throws Exception{ closeClient(); openClient(); } private static void openClient() throws Exception { allocator = RootAllocatorFactory.newRoot(config); if (config.hasPath(ENABLE_FULL_CACHE) && config.getBoolean(ENABLE_FULL_CACHE)) { serviceSet = RemoteServiceSet.getServiceSetWithFullCache(config, allocator); } else { serviceSet = RemoteServiceSet.getLocalServiceSet(); } dfsTestTmpSchemaLocation = TestUtilities.createTempDir(); bits = new Drillbit[drillbitCount]; for(int i = 0; i < drillbitCount; i++) { bits[i] = new Drillbit(config, serviceSet, classpathScan); bits[i].run(); final StoragePluginRegistry pluginRegistry = bits[i].getContext().getStorage(); TestUtilities.updateDfsTestTmpSchemaLocation(pluginRegistry, dfsTestTmpSchemaLocation); TestUtilities.makeDfsTmpSchemaImmutable(pluginRegistry); } client = QueryTestUtil.createClient(config, serviceSet, MAX_WIDTH_PER_NODE, null); } /** * Close the current <i>client</i> and open a new client using the given <i>properties</i>. All tests executed * after this method call use the new <i>client</i>. * * @param properties */ public static void updateClient(Properties properties) throws Exception { Preconditions.checkState(bits != null && bits[0] != null, "Drillbits are not setup."); if (client != null) { client.close(); client = null; } client = QueryTestUtil.createClient(config, serviceSet, MAX_WIDTH_PER_NODE, properties); } /* * Close the current <i>client</i> and open a new client for the given user. All tests executed * after this method call use the new <i>client</i>. * @param user */ public static void updateClient(String user) throws Exception { updateClient(user, null); } /* * Close the current <i>client</i> and open a new client for the given user and password credentials. Tests * executed after this method call use the new <i>client</i>. * @param user */ public static void updateClient(final String user, final String password) throws Exception { final Properties props = new Properties(); props.setProperty(UserSession.USER, user); if (password != null) { props.setProperty(UserSession.PASSWORD, password); } updateClient(props); } protected static BufferAllocator getAllocator() { return allocator; } public static TestBuilder newTest() { return testBuilder(); } public static TestBuilder testBuilder() { return new TestBuilder(allocator); } @AfterClass public static void closeClient() throws IOException { if (client != null) { client.close(); } if (bits != null) { for(final Drillbit bit : bits) { if (bit != null) { bit.close(); } } } if(serviceSet != null) { serviceSet.close(); } if (allocator != null) { allocator.close(); } } @AfterClass public static void resetDrillbitCount() { // some test classes assume this value to be 1 and will fail if run along other tests that increase it drillbitCount = 1; } protected static void runSQL(String sql) throws Exception { final AwaitableUserResultsListener listener = new AwaitableUserResultsListener(new SilentListener()); testWithListener(QueryType.SQL, sql, listener); listener.await(); } protected static List<QueryDataBatch> testSqlWithResults(String sql) throws Exception{ return testRunAndReturn(QueryType.SQL, sql); } protected static List<QueryDataBatch> testLogicalWithResults(String logical) throws Exception{ return testRunAndReturn(QueryType.LOGICAL, logical); } protected static List<QueryDataBatch> testPhysicalWithResults(String physical) throws Exception{ return testRunAndReturn(QueryType.PHYSICAL, physical); } public static List<QueryDataBatch> testRunAndReturn(QueryType type, String query) throws Exception{ query = QueryTestUtil.normalizeQuery(query); return client.runQuery(type, query); } public static int testRunAndPrint(final QueryType type, final String query) throws Exception { return QueryTestUtil.testRunAndPrint(client, type, query); } protected static void testWithListener(QueryType type, String query, UserResultsListener resultListener) { QueryTestUtil.testWithListener(client, type, query, resultListener); } public static void testNoResult(String query, Object... args) throws Exception { testNoResult(1, query, args); } protected static void testNoResult(int interation, String query, Object... args) throws Exception { query = String.format(query, args); logger.debug("Running query:\n--------------\n" + query); for (int i = 0; i < interation; i++) { final List<QueryDataBatch> results = client.runQuery(QueryType.SQL, query); for (final QueryDataBatch queryDataBatch : results) { queryDataBatch.release(); } } } public static void test(String query, Object... args) throws Exception { QueryTestUtil.test(client, String.format(query, args)); } public static void test(final String query) throws Exception { QueryTestUtil.test(client, query); } protected static int testLogical(String query) throws Exception{ return testRunAndPrint(QueryType.LOGICAL, query); } protected static int testPhysical(String query) throws Exception{ return testRunAndPrint(QueryType.PHYSICAL, query); } protected static int testSql(String query) throws Exception{ return testRunAndPrint(QueryType.SQL, query); } protected static void testPhysicalFromFile(String file) throws Exception{ testPhysical(getFile(file)); } protected static List<QueryDataBatch> testPhysicalFromFileWithResults(String file) throws Exception { return testRunAndReturn(QueryType.PHYSICAL, getFile(file)); } protected static void testLogicalFromFile(String file) throws Exception{ testLogical(getFile(file)); } protected static void testSqlFromFile(String file) throws Exception{ test(getFile(file)); } /** * Utility method which tests given query produces a {@link UserException} and the exception message contains * the given message. * @param testSqlQuery Test query * @param expectedErrorMsg Expected error message. */ protected static void errorMsgTestHelper(final String testSqlQuery, final String expectedErrorMsg) throws Exception { try { test(testSqlQuery); fail("Expected a UserException when running " + testSqlQuery); } catch (final UserException actualException) { try { assertThat("message of UserException when running " + testSqlQuery, actualException.getMessage(), containsString(expectedErrorMsg)); } catch (AssertionError e) { e.addSuppressed(actualException); throw e; } } } /** * Utility method which tests given query produces a {@link UserException} * with {@link org.apache.drill.exec.proto.UserBitShared.DrillPBError.ErrorType} being DrillPBError.ErrorType.PARSE * the given message. * @param testSqlQuery Test query */ protected static void parseErrorHelper(final String testSqlQuery) throws Exception { errorMsgTestHelper(testSqlQuery, UserBitShared.DrillPBError.ErrorType.PARSE.name()); } public static String getFile(String resource) throws IOException{ final URL url = Resources.getResource(resource); if (url == null) { throw new IOException(String.format("Unable to find path %s.", resource)); } return Resources.toString(url, Charsets.UTF_8); } /** * Copy the resource (ex. file on classpath) to a physical file on FileSystem. * @param resource * @return the file path * @throws IOException */ public static String getPhysicalFileFromResource(final String resource) throws IOException { final File file = File.createTempFile("tempfile", ".txt"); file.deleteOnExit(); final PrintWriter printWriter = new PrintWriter(file); printWriter.write(BaseTestQuery.getFile(resource)); printWriter.close(); return file.getPath(); } /** * Create a temp directory to store the given <i>dirName</i> * @param dirName * @return Full path including temp parent directory and given directory name. */ public static String getTempDir(final String dirName) { final File dir = Files.createTempDir(); dir.deleteOnExit(); return dir.getAbsolutePath() + File.separator + dirName; } protected static void setSessionOption(final String option, final String value) { try { runSQL(String.format("alter session set `%s` = %s", option, value)); } catch(final Exception e) { fail(String.format("Failed to set session option `%s` = %s, Error: %s", option, value, e.toString())); } } public static class SilentListener implements UserResultsListener { private final AtomicInteger count = new AtomicInteger(); @Override public void submissionFailed(UserException ex) { logger.debug("Query failed: " + ex.getMessage()); } @Override public void queryCompleted(QueryState state) { logger.debug("Query completed successfully with row count: " + count.get()); } @Override public void dataArrived(QueryDataBatch result, ConnectionThrottle throttle) { final int rows = result.getHeader().getRowCount(); if (result.getData() != null) { count.addAndGet(rows); } result.release(); } @Override public void queryIdArrived(QueryId queryId) {} } protected void setColumnWidth(int columnWidth) { this.columnWidths = new int[] { columnWidth }; } protected void setColumnWidths(int[] columnWidths) { this.columnWidths = columnWidths; } protected int printResult(List<QueryDataBatch> results) throws SchemaChangeException { int rowCount = 0; final RecordBatchLoader loader = new RecordBatchLoader(getAllocator()); for(final QueryDataBatch result : results) { rowCount += result.getHeader().getRowCount(); loader.load(result.getHeader().getDef(), result.getData()); // TODO: Clean: DRILL-2933: That load(...) no longer throws // SchemaChangeException, so check/clean throw clause above. VectorUtil.showVectorAccessibleContent(loader, columnWidths); loader.clear(); result.release(); } System.out.println("Total record count: " + rowCount); return rowCount; } protected static String getResultString(List<QueryDataBatch> results, String delimiter) throws SchemaChangeException { final StringBuilder formattedResults = new StringBuilder(); boolean includeHeader = true; final RecordBatchLoader loader = new RecordBatchLoader(getAllocator()); for(final QueryDataBatch result : results) { loader.load(result.getHeader().getDef(), result.getData()); if (loader.getRecordCount() <= 0) { continue; } VectorUtil.appendVectorAccessibleContent(loader, formattedResults, delimiter, includeHeader); if (!includeHeader) { includeHeader = false; } loader.clear(); result.release(); } return formattedResults.toString(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.runtime.tasks; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.functions.RichMapFunction; import org.apache.flink.api.common.state.ListState; import org.apache.flink.api.common.state.ListStateDescriptor; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeutils.base.IntSerializer; import org.apache.flink.api.common.typeutils.base.StringSerializer; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.testutils.OneShotLatch; import org.apache.flink.metrics.Counter; import org.apache.flink.metrics.Gauge; import org.apache.flink.runtime.checkpoint.CheckpointMetaData; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.TaskStateSnapshot; import org.apache.flink.runtime.io.network.api.CancelCheckpointMarker; import org.apache.flink.runtime.io.network.api.CheckpointBarrier; import org.apache.flink.runtime.jobgraph.OperatorID; import org.apache.flink.runtime.metrics.MetricNames; import org.apache.flink.runtime.metrics.NoOpMetricRegistry; import org.apache.flink.runtime.metrics.groups.OperatorMetricGroup; import org.apache.flink.runtime.metrics.groups.TaskMetricGroup; import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups; import org.apache.flink.runtime.metrics.util.InterceptingOperatorMetricGroup; import org.apache.flink.runtime.metrics.util.InterceptingTaskMetricGroup; import org.apache.flink.runtime.operators.testutils.MockInputSplitProvider; import org.apache.flink.runtime.state.StateInitializationContext; import org.apache.flink.runtime.state.StateSnapshotContext; import org.apache.flink.runtime.state.TestTaskStateManager; import org.apache.flink.streaming.api.graph.StreamConfig; import org.apache.flink.streaming.api.graph.StreamEdge; import org.apache.flink.streaming.api.graph.StreamNode; import org.apache.flink.streaming.api.operators.AbstractStreamOperator; import org.apache.flink.streaming.api.operators.OneInputStreamOperator; import org.apache.flink.streaming.api.operators.StreamMap; import org.apache.flink.streaming.api.watermark.Watermark; import org.apache.flink.streaming.runtime.streamrecord.StreamRecord; import org.apache.flink.streaming.runtime.streamstatus.StreamStatus; import org.apache.flink.streaming.util.TestHarnessUtil; import org.apache.flink.util.Preconditions; import org.apache.flink.util.TestLogger; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; 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 java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import scala.concurrent.duration.Deadline; import scala.concurrent.duration.FiniteDuration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Tests for {@link OneInputStreamTask}. * * <p>Note:<br> * We only use a {@link StreamMap} operator here. We also test the individual operators but Map is * used as a representative to test OneInputStreamTask, since OneInputStreamTask is used for all * OneInputStreamOperators. */ public class OneInputStreamTaskTest extends TestLogger { private static final ListStateDescriptor<Integer> TEST_DESCRIPTOR = new ListStateDescriptor<>("test", new IntSerializer()); /** * This test verifies that open() and close() are correctly called. This test also verifies * that timestamps of emitted elements are correct. {@link StreamMap} assigns the input * timestamp to emitted elements. */ @Test public void testOpenCloseAndTimestamps() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); StreamMap<String, String> mapOperator = new StreamMap<String, String>(new TestOpenCloseMapFunction()); streamConfig.setStreamOperator(mapOperator); streamConfig.setOperatorID(new OperatorID()); long initialTime = 0L; ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<Object>(); testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processElement(new StreamRecord<String>("Hello", initialTime + 1)); testHarness.processElement(new StreamRecord<String>("Ciao", initialTime + 2)); expectedOutput.add(new StreamRecord<String>("Hello", initialTime + 1)); expectedOutput.add(new StreamRecord<String>("Ciao", initialTime + 2)); testHarness.endInput(); testHarness.waitForTaskCompletion(); assertTrue("RichFunction methods where not called.", TestOpenCloseMapFunction.closeCalled); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); } /** * This test verifies that watermarks and stream statuses are correctly forwarded. This also checks whether * watermarks are forwarded only when we have received watermarks from all inputs. The * forwarded watermark must be the minimum of the watermarks of all active inputs. */ @Test @SuppressWarnings("unchecked") public void testWatermarkAndStreamStatusForwarding() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, 2, 2, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); StreamMap<String, String> mapOperator = new StreamMap<String, String>(new IdentityMap()); streamConfig.setStreamOperator(mapOperator); streamConfig.setOperatorID(new OperatorID()); ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<Object>(); long initialTime = 0L; testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processElement(new Watermark(initialTime), 0, 0); testHarness.processElement(new Watermark(initialTime), 0, 1); testHarness.processElement(new Watermark(initialTime), 1, 0); // now the output should still be empty testHarness.waitForInputProcessing(); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.processElement(new Watermark(initialTime), 1, 1); // now the watermark should have propagated, Map simply forward Watermarks testHarness.waitForInputProcessing(); expectedOutput.add(new Watermark(initialTime)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // contrary to checkpoint barriers these elements are not blocked by watermarks testHarness.processElement(new StreamRecord<String>("Hello", initialTime)); testHarness.processElement(new StreamRecord<String>("Ciao", initialTime)); expectedOutput.add(new StreamRecord<String>("Hello", initialTime)); expectedOutput.add(new StreamRecord<String>("Ciao", initialTime)); testHarness.processElement(new Watermark(initialTime + 4), 0, 0); testHarness.processElement(new Watermark(initialTime + 3), 0, 1); testHarness.processElement(new Watermark(initialTime + 3), 1, 0); testHarness.processElement(new Watermark(initialTime + 2), 1, 1); // check whether we get the minimum of all the watermarks, this must also only occur in // the output after the two StreamRecords testHarness.waitForInputProcessing(); expectedOutput.add(new Watermark(initialTime + 2)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // advance watermark from one of the inputs, now we should get a new one since the // minimum increases testHarness.processElement(new Watermark(initialTime + 4), 1, 1); testHarness.waitForInputProcessing(); expectedOutput.add(new Watermark(initialTime + 3)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // advance the other two inputs, now we should get a new one since the // minimum increases again testHarness.processElement(new Watermark(initialTime + 4), 0, 1); testHarness.processElement(new Watermark(initialTime + 4), 1, 0); testHarness.waitForInputProcessing(); expectedOutput.add(new Watermark(initialTime + 4)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // test whether idle input channels are acknowledged correctly when forwarding watermarks testHarness.processElement(StreamStatus.IDLE, 0, 1); testHarness.processElement(StreamStatus.IDLE, 1, 0); testHarness.processElement(new Watermark(initialTime + 6), 0, 0); testHarness.processElement(new Watermark(initialTime + 5), 1, 1); // this watermark should be advanced first testHarness.processElement(StreamStatus.IDLE, 1, 1); // once this is acknowledged, // watermark (initial + 6) should be forwarded testHarness.waitForInputProcessing(); expectedOutput.add(new Watermark(initialTime + 5)); expectedOutput.add(new Watermark(initialTime + 6)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // make all input channels idle and check that the operator's idle status is forwarded testHarness.processElement(StreamStatus.IDLE, 0, 0); testHarness.waitForInputProcessing(); expectedOutput.add(StreamStatus.IDLE); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // make some input channels active again and check that the operator's active status is forwarded only once testHarness.processElement(StreamStatus.ACTIVE, 1, 0); testHarness.processElement(StreamStatus.ACTIVE, 0, 1); testHarness.waitForInputProcessing(); expectedOutput.add(StreamStatus.ACTIVE); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.endInput(); testHarness.waitForTaskCompletion(); List<String> resultElements = TestHarnessUtil.getRawElementsFromOutput(testHarness.getOutput()); assertEquals(2, resultElements.size()); } /** * This test verifies that watermarks are not forwarded when the task is idle. * It also verifies that when task is idle, watermarks generated in the middle of chains are also blocked and * never forwarded. * * <p>The tested chain will be: (HEAD: normal operator) --> (watermark generating operator) --> (normal operator). * The operators will throw an exception and fail the test if either of them were forwarded watermarks when * the task is idle. */ @Test public void testWatermarksNotForwardedWithinChainWhenIdle() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, 1, 1, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); TriggerableFailOnWatermarkTestOperator headOperator = new TriggerableFailOnWatermarkTestOperator(); WatermarkGeneratingTestOperator watermarkOperator = new WatermarkGeneratingTestOperator(); TriggerableFailOnWatermarkTestOperator tailOperator = new TriggerableFailOnWatermarkTestOperator(); testHarness.setupOperatorChain(new OperatorID(42L, 42L), headOperator) .chain(new OperatorID(4711L, 42L), watermarkOperator, StringSerializer.INSTANCE) .chain(new OperatorID(123L, 123L), tailOperator, StringSerializer.INSTANCE) .finish(); // --------------------- begin test --------------------- ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<Object>(); testHarness.invoke(); testHarness.waitForTaskRunning(); // the task starts as active, so all generated watermarks should be forwarded testHarness.processElement(new StreamRecord<>(TriggerableFailOnWatermarkTestOperator.EXPECT_FORWARDED_WATERMARKS_MARKER)); testHarness.processElement(new StreamRecord<>("10"), 0, 0); // this watermark will be forwarded since the task is currently active, // but should not be in the final output because it should be blocked by the watermark generator in the chain testHarness.processElement(new Watermark(15)); testHarness.processElement(new StreamRecord<>("20"), 0, 0); testHarness.processElement(new StreamRecord<>("30"), 0, 0); testHarness.waitForInputProcessing(); expectedOutput.add(new StreamRecord<>(TriggerableFailOnWatermarkTestOperator.EXPECT_FORWARDED_WATERMARKS_MARKER)); expectedOutput.add(new StreamRecord<>("10")); expectedOutput.add(new Watermark(10)); expectedOutput.add(new StreamRecord<>("20")); expectedOutput.add(new Watermark(20)); expectedOutput.add(new StreamRecord<>("30")); expectedOutput.add(new Watermark(30)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // now, toggle the task to be idle, and let the watermark generator produce some watermarks testHarness.processElement(StreamStatus.IDLE); // after this, the operators will throw an exception if they are forwarded watermarks anywhere in the chain testHarness.processElement(new StreamRecord<>(TriggerableFailOnWatermarkTestOperator.NO_FORWARDED_WATERMARKS_MARKER)); // NOTE: normally, tasks will not have records to process while idle; // we're doing this here only to mimic watermark generating in operators testHarness.processElement(new StreamRecord<>("40"), 0, 0); testHarness.processElement(new StreamRecord<>("50"), 0, 0); testHarness.processElement(new StreamRecord<>("60"), 0, 0); testHarness.processElement(new Watermark(65)); // the test will fail if any of the operators were forwarded this testHarness.waitForInputProcessing(); // the 40 - 60 watermarks should not be forwarded, only the stream status toggle element and records expectedOutput.add(StreamStatus.IDLE); expectedOutput.add(new StreamRecord<>(TriggerableFailOnWatermarkTestOperator.NO_FORWARDED_WATERMARKS_MARKER)); expectedOutput.add(new StreamRecord<>("40")); expectedOutput.add(new StreamRecord<>("50")); expectedOutput.add(new StreamRecord<>("60")); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // re-toggle the task to be active and see if new watermarks are correctly forwarded again testHarness.processElement(StreamStatus.ACTIVE); testHarness.processElement(new StreamRecord<>(TriggerableFailOnWatermarkTestOperator.EXPECT_FORWARDED_WATERMARKS_MARKER)); testHarness.processElement(new StreamRecord<>("70"), 0, 0); testHarness.processElement(new StreamRecord<>("80"), 0, 0); testHarness.processElement(new StreamRecord<>("90"), 0, 0); testHarness.waitForInputProcessing(); expectedOutput.add(StreamStatus.ACTIVE); expectedOutput.add(new StreamRecord<>(TriggerableFailOnWatermarkTestOperator.EXPECT_FORWARDED_WATERMARKS_MARKER)); expectedOutput.add(new StreamRecord<>("70")); expectedOutput.add(new Watermark(70)); expectedOutput.add(new StreamRecord<>("80")); expectedOutput.add(new Watermark(80)); expectedOutput.add(new StreamRecord<>("90")); expectedOutput.add(new Watermark(90)); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.endInput(); testHarness.waitForTaskCompletion(); List<String> resultElements = TestHarnessUtil.getRawElementsFromOutput(testHarness.getOutput()); assertEquals(12, resultElements.size()); } /** * This test verifies that checkpoint barriers are correctly forwarded. */ @Test public void testCheckpointBarriers() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, 2, 2, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); StreamMap<String, String> mapOperator = new StreamMap<String, String>(new IdentityMap()); streamConfig.setStreamOperator(mapOperator); streamConfig.setOperatorID(new OperatorID()); ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<Object>(); long initialTime = 0L; testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0); // These elements should be buffered until we receive barriers from // all inputs testHarness.processElement(new StreamRecord<String>("Hello-0-0", initialTime), 0, 0); testHarness.processElement(new StreamRecord<String>("Ciao-0-0", initialTime), 0, 0); // These elements should be forwarded, since we did not yet receive a checkpoint barrier // on that input, only add to same input, otherwise we would not know the ordering // of the output since the Task might read the inputs in any order testHarness.processElement(new StreamRecord<String>("Hello-1-1", initialTime), 1, 1); testHarness.processElement(new StreamRecord<String>("Ciao-1-1", initialTime), 1, 1); expectedOutput.add(new StreamRecord<String>("Hello-1-1", initialTime)); expectedOutput.add(new StreamRecord<String>("Ciao-1-1", initialTime)); testHarness.waitForInputProcessing(); // we should not yet see the barrier, only the two elements from non-blocked input TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1); testHarness.waitForInputProcessing(); // now we should see the barrier and after that the buffered elements expectedOutput.add(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation())); expectedOutput.add(new StreamRecord<String>("Hello-0-0", initialTime)); expectedOutput.add(new StreamRecord<String>("Ciao-0-0", initialTime)); testHarness.endInput(); testHarness.waitForTaskCompletion(); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); } /** * This test verifies that checkpoint barriers and barrier buffers work correctly with * concurrent checkpoint barriers where one checkpoint is "overtaking" another checkpoint, i.e. * some inputs receive barriers from an earlier checkpoint, thereby blocking, * then all inputs receive barriers from a later checkpoint. */ @Test public void testOvertakingCheckpointBarriers() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, 2, 2, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); StreamMap<String, String> mapOperator = new StreamMap<String, String>(new IdentityMap()); streamConfig.setStreamOperator(mapOperator); streamConfig.setOperatorID(new OperatorID()); ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<Object>(); long initialTime = 0L; testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0); // These elements should be buffered until we receive barriers from // all inputs testHarness.processElement(new StreamRecord<String>("Hello-0-0", initialTime), 0, 0); testHarness.processElement(new StreamRecord<String>("Ciao-0-0", initialTime), 0, 0); // These elements should be forwarded, since we did not yet receive a checkpoint barrier // on that input, only add to same input, otherwise we would not know the ordering // of the output since the Task might read the inputs in any order testHarness.processElement(new StreamRecord<String>("Hello-1-1", initialTime), 1, 1); testHarness.processElement(new StreamRecord<String>("Ciao-1-1", initialTime), 1, 1); expectedOutput.add(new StreamRecord<String>("Hello-1-1", initialTime)); expectedOutput.add(new StreamRecord<String>("Ciao-1-1", initialTime)); testHarness.waitForInputProcessing(); // we should not yet see the barrier, only the two elements from non-blocked input TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // Now give a later barrier to all inputs, this should unblock the first channel, // thereby allowing the two blocked elements through testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0); testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1); testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0); testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1); expectedOutput.add(new CancelCheckpointMarker(0)); expectedOutput.add(new StreamRecord<String>("Hello-0-0", initialTime)); expectedOutput.add(new StreamRecord<String>("Ciao-0-0", initialTime)); expectedOutput.add(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation())); testHarness.waitForInputProcessing(); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); // Then give the earlier barrier, these should be ignored testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0); testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1); testHarness.waitForInputProcessing(); testHarness.endInput(); testHarness.waitForTaskCompletion(); TestHarnessUtil.assertOutputEquals("Output was not correct.", expectedOutput, testHarness.getOutput()); } /** * Tests that the stream operator can snapshot and restore the operator state of chained * operators. */ @Test public void testSnapshottingAndRestoring() throws Exception { final Deadline deadline = new FiniteDuration(2, TimeUnit.MINUTES).fromNow(); final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); IdentityKeySelector<String> keySelector = new IdentityKeySelector<>(); testHarness.configureForKeyedStream(keySelector, BasicTypeInfo.STRING_TYPE_INFO); long checkpointId = 1L; long checkpointTimestamp = 1L; int numberChainedTasks = 11; StreamConfig streamConfig = testHarness.getStreamConfig(); configureChainedTestingStreamOperator(streamConfig, numberChainedTasks); TestTaskStateManager taskStateManager = testHarness.taskStateManager; OneShotLatch waitForAcknowledgeLatch = new OneShotLatch(); taskStateManager.setWaitForReportLatch(waitForAcknowledgeLatch); // reset number of restore calls TestingStreamOperator.numberRestoreCalls = 0; testHarness.invoke(); testHarness.waitForTaskRunning(deadline.timeLeft().toMillis()); final OneInputStreamTask<String, String> streamTask = testHarness.getTask(); CheckpointMetaData checkpointMetaData = new CheckpointMetaData(checkpointId, checkpointTimestamp); while (!streamTask.triggerCheckpoint(checkpointMetaData, CheckpointOptions.forCheckpointWithDefaultLocation())) {} // since no state was set, there shouldn't be restore calls assertEquals(0, TestingStreamOperator.numberRestoreCalls); waitForAcknowledgeLatch.await(); assertEquals(checkpointId, taskStateManager.getReportedCheckpointId()); testHarness.endInput(); testHarness.waitForTaskCompletion(deadline.timeLeft().toMillis()); final OneInputStreamTaskTestHarness<String, String> restoredTaskHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); restoredTaskHarness.configureForKeyedStream(keySelector, BasicTypeInfo.STRING_TYPE_INFO); restoredTaskHarness.setTaskStateSnapshot(checkpointId, taskStateManager.getLastJobManagerTaskStateSnapshot()); StreamConfig restoredTaskStreamConfig = restoredTaskHarness.getStreamConfig(); configureChainedTestingStreamOperator(restoredTaskStreamConfig, numberChainedTasks); TaskStateSnapshot stateHandles = taskStateManager.getLastJobManagerTaskStateSnapshot(); Assert.assertEquals(numberChainedTasks, stateHandles.getSubtaskStateMappings().size()); TestingStreamOperator.numberRestoreCalls = 0; // transfer state to new harness restoredTaskHarness.taskStateManager.restoreLatestCheckpointState( taskStateManager.getJobManagerTaskStateSnapshotsByCheckpointId()); restoredTaskHarness.invoke(); restoredTaskHarness.endInput(); restoredTaskHarness.waitForTaskCompletion(deadline.timeLeft().toMillis()); // restore of every chained operator should have been called assertEquals(numberChainedTasks, TestingStreamOperator.numberRestoreCalls); TestingStreamOperator.numberRestoreCalls = 0; } @Test public void testQuiesceTimerServiceAfterOpClose() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, 2, 2, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); streamConfig.setStreamOperator(new TestOperator()); streamConfig.setOperatorID(new OperatorID()); testHarness.invoke(); testHarness.waitForTaskRunning(); SystemProcessingTimeService timeService = (SystemProcessingTimeService) testHarness.getTask().getProcessingTimeService(); // verify that the timer service is running Assert.assertTrue(timeService.isAlive()); testHarness.endInput(); testHarness.waitForTaskCompletion(); timeService.shutdownService(); } private static class TestOperator extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> { private static final long serialVersionUID = 1L; @Override public void processElement(StreamRecord<String> element) throws Exception { output.collect(element); } @Override public void close() throws Exception { // verify that the timer service is still running Assert.assertTrue( ((SystemProcessingTimeService) getContainingTask().getProcessingTimeService()) .isAlive()); super.close(); } } @Test public void testOperatorMetricReuse() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>(OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOperatorChain(new OperatorID(), new DuplicatingOperator()) .chain(new OperatorID(), new DuplicatingOperator(), BasicTypeInfo.STRING_TYPE_INFO.createSerializer(new ExecutionConfig())) .chain(new OperatorID(), new DuplicatingOperator(), BasicTypeInfo.STRING_TYPE_INFO.createSerializer(new ExecutionConfig())) .finish(); final TaskMetricGroup taskMetricGroup = new UnregisteredMetricGroups.UnregisteredTaskMetricGroup() { @Override public OperatorMetricGroup getOrAddOperator(OperatorID operatorID, String name) { return new OperatorMetricGroup(NoOpMetricRegistry.INSTANCE, this, operatorID, name); } }; final StreamMockEnvironment env = new StreamMockEnvironment( testHarness.jobConfig, testHarness.taskConfig, testHarness.memorySize, new MockInputSplitProvider(), testHarness.bufferSize, new TestTaskStateManager()) { @Override public TaskMetricGroup getMetricGroup() { return taskMetricGroup; } }; final Counter numRecordsInCounter = taskMetricGroup.getIOMetricGroup().getNumRecordsInCounter(); final Counter numRecordsOutCounter = taskMetricGroup.getIOMetricGroup().getNumRecordsOutCounter(); testHarness.invoke(env); testHarness.waitForTaskRunning(); final int numRecords = 5; for (int x = 0; x < numRecords; x++) { testHarness.processElement(new StreamRecord<>("hello")); } testHarness.waitForInputProcessing(); assertEquals(numRecords, numRecordsInCounter.getCount()); assertEquals(numRecords * 2 * 2 * 2, numRecordsOutCounter.getCount()); } static class DuplicatingOperator extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> { @Override public void processElement(StreamRecord<String> element) { output.collect(element); output.collect(element); } } @Test public void testWatermarkMetrics() throws Exception { final OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>(OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); OneInputStreamOperator<String, String> headOperator = new WatermarkMetricOperator(); OperatorID headOperatorId = new OperatorID(); OneInputStreamOperator<String, String> chainedOperator = new WatermarkMetricOperator(); OperatorID chainedOperatorId = new OperatorID(); testHarness.setupOperatorChain(headOperatorId, headOperator) .chain(chainedOperatorId, chainedOperator, BasicTypeInfo.STRING_TYPE_INFO.createSerializer(new ExecutionConfig())) .finish(); InterceptingOperatorMetricGroup headOperatorMetricGroup = new InterceptingOperatorMetricGroup(); InterceptingOperatorMetricGroup chainedOperatorMetricGroup = new InterceptingOperatorMetricGroup(); InterceptingTaskMetricGroup taskMetricGroup = new InterceptingTaskMetricGroup() { @Override public OperatorMetricGroup getOrAddOperator(OperatorID id, String name) { if (id.equals(headOperatorId)) { return headOperatorMetricGroup; } else if (id.equals(chainedOperatorId)) { return chainedOperatorMetricGroup; } else { return super.getOrAddOperator(id, name); } } }; StreamMockEnvironment env = new StreamMockEnvironment( testHarness.jobConfig, testHarness.taskConfig, testHarness.memorySize, new MockInputSplitProvider(), testHarness.bufferSize, new TestTaskStateManager()) { @Override public TaskMetricGroup getMetricGroup() { return taskMetricGroup; } }; testHarness.invoke(env); testHarness.waitForTaskRunning(); Gauge<Long> taskInputWatermarkGauge = (Gauge<Long>) taskMetricGroup.get(MetricNames.IO_CURRENT_INPUT_WATERMARK); Gauge<Long> headInputWatermarkGauge = (Gauge<Long>) headOperatorMetricGroup.get(MetricNames.IO_CURRENT_INPUT_WATERMARK); Gauge<Long> headOutputWatermarkGauge = (Gauge<Long>) headOperatorMetricGroup.get(MetricNames.IO_CURRENT_OUTPUT_WATERMARK); Gauge<Long> chainedInputWatermarkGauge = (Gauge<Long>) chainedOperatorMetricGroup.get(MetricNames.IO_CURRENT_INPUT_WATERMARK); Gauge<Long> chainedOutputWatermarkGauge = (Gauge<Long>) chainedOperatorMetricGroup.get(MetricNames.IO_CURRENT_OUTPUT_WATERMARK); Assert.assertEquals("A metric was registered multiple times.", 5, new HashSet<>(Arrays.asList( taskInputWatermarkGauge, headInputWatermarkGauge, headOutputWatermarkGauge, chainedInputWatermarkGauge, chainedOutputWatermarkGauge)) .size()); Assert.assertEquals(Long.MIN_VALUE, taskInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(Long.MIN_VALUE, headInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(Long.MIN_VALUE, headOutputWatermarkGauge.getValue().longValue()); Assert.assertEquals(Long.MIN_VALUE, chainedInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(Long.MIN_VALUE, chainedOutputWatermarkGauge.getValue().longValue()); testHarness.processElement(new Watermark(1L)); testHarness.waitForInputProcessing(); Assert.assertEquals(1L, taskInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(1L, headInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(2L, headOutputWatermarkGauge.getValue().longValue()); Assert.assertEquals(2L, chainedInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(4L, chainedOutputWatermarkGauge.getValue().longValue()); testHarness.processElement(new Watermark(2L)); testHarness.waitForInputProcessing(); Assert.assertEquals(2L, taskInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(2L, headInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(4L, headOutputWatermarkGauge.getValue().longValue()); Assert.assertEquals(4L, chainedInputWatermarkGauge.getValue().longValue()); Assert.assertEquals(8L, chainedOutputWatermarkGauge.getValue().longValue()); testHarness.endInput(); testHarness.waitForTaskCompletion(); } static class WatermarkMetricOperator extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> { @Override public void processElement(StreamRecord<String> element) throws Exception { output.collect(element); } @Override public void processWatermark(Watermark mark) throws Exception { output.emitWatermark(new Watermark(mark.getTimestamp() * 2)); } } //============================================================================================== // Utility functions and classes //============================================================================================== private void configureChainedTestingStreamOperator( StreamConfig streamConfig, int numberChainedTasks) { Preconditions.checkArgument(numberChainedTasks >= 1, "The operator chain must at least " + "contain one operator."); TestingStreamOperator<Integer, Integer> previousOperator = new TestingStreamOperator<>(); streamConfig.setStreamOperator(previousOperator); streamConfig.setOperatorID(new OperatorID(0L, 0L)); // create the chain of operators Map<Integer, StreamConfig> chainedTaskConfigs = new HashMap<>(numberChainedTasks - 1); List<StreamEdge> outputEdges = new ArrayList<>(numberChainedTasks - 1); for (int chainedIndex = 1; chainedIndex < numberChainedTasks; chainedIndex++) { TestingStreamOperator<Integer, Integer> chainedOperator = new TestingStreamOperator<>(); StreamConfig chainedConfig = new StreamConfig(new Configuration()); chainedConfig.setStreamOperator(chainedOperator); chainedConfig.setOperatorID(new OperatorID(0L, chainedIndex)); chainedTaskConfigs.put(chainedIndex, chainedConfig); StreamEdge outputEdge = new StreamEdge( new StreamNode( null, chainedIndex - 1, null, null, null, null, null, null ), new StreamNode( null, chainedIndex, null, null, null, null, null, null ), 0, Collections.<String>emptyList(), null, null ); outputEdges.add(outputEdge); } streamConfig.setChainedOutputs(outputEdges); streamConfig.setTransitiveChainedTaskConfigs(chainedTaskConfigs); } private static class IdentityKeySelector<IN> implements KeySelector<IN, IN> { private static final long serialVersionUID = -3555913664416688425L; @Override public IN getKey(IN value) throws Exception { return value; } } private static class TestingStreamOperator<IN, OUT> extends AbstractStreamOperator<OUT> implements OneInputStreamOperator<IN, OUT> { private static final long serialVersionUID = 774614855940397174L; public static int numberRestoreCalls = 0; public static int numberSnapshotCalls = 0; @Override public void snapshotState(StateSnapshotContext context) throws Exception { ListState<Integer> partitionableState = getOperatorStateBackend().getListState(TEST_DESCRIPTOR); partitionableState.clear(); partitionableState.add(42); partitionableState.add(4711); ++numberSnapshotCalls; } @Override public void initializeState(StateInitializationContext context) throws Exception { if (context.isRestored()) { ++numberRestoreCalls; } ListState<Integer> partitionableState = context.getOperatorStateStore().getListState(TEST_DESCRIPTOR); if (numberSnapshotCalls == 0) { for (Integer v : partitionableState.get()) { fail(); } } else { Set<Integer> result = new HashSet<>(); for (Integer v : partitionableState.get()) { result.add(v); } assertEquals(2, result.size()); assertTrue(result.contains(42)); assertTrue(result.contains(4711)); } } @Override public void processElement(StreamRecord<IN> element) throws Exception { } } // This must only be used in one test, otherwise the static fields will be changed // by several tests concurrently private static class TestOpenCloseMapFunction extends RichMapFunction<String, String> { private static final long serialVersionUID = 1L; public static boolean openCalled = false; public static boolean closeCalled = false; @Override public void open(Configuration parameters) throws Exception { super.open(parameters); if (closeCalled) { Assert.fail("Close called before open."); } openCalled = true; } @Override public void close() throws Exception { super.close(); if (!openCalled) { Assert.fail("Open was not called before close."); } closeCalled = true; } @Override public String map(String value) throws Exception { if (!openCalled) { Assert.fail("Open was not called before run."); } return value; } } private static class IdentityMap implements MapFunction<String, String> { private static final long serialVersionUID = 1L; @Override public String map(String value) throws Exception { return value; } } /** * A {@link TriggerableFailOnWatermarkTestOperator} that generates watermarks. */ private static class WatermarkGeneratingTestOperator extends TriggerableFailOnWatermarkTestOperator { private static final long serialVersionUID = -5064871833244157221L; private long lastWatermark; @Override protected void handleElement(StreamRecord<String> element) { long timestamp = Long.valueOf(element.getValue()); if (timestamp > lastWatermark) { output.emitWatermark(new Watermark(timestamp)); lastWatermark = timestamp; } } @Override protected void handleWatermark(Watermark mark) { if (mark.equals(Watermark.MAX_WATERMARK)) { output.emitWatermark(mark); lastWatermark = Long.MAX_VALUE; } } } /** * An operator that can be triggered whether or not to expect watermarks forwarded to it, toggled * by letting it process special trigger marker records. * * <p>If it receives a watermark when it's not expecting one, it'll throw an exception and fail. */ private static class TriggerableFailOnWatermarkTestOperator extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> { private static final long serialVersionUID = 2048954179291813243L; public static final String EXPECT_FORWARDED_WATERMARKS_MARKER = "EXPECT_WATERMARKS"; public static final String NO_FORWARDED_WATERMARKS_MARKER = "NO_WATERMARKS"; protected boolean expectForwardedWatermarks; @Override public void processElement(StreamRecord<String> element) throws Exception { output.collect(element); if (element.getValue().equals(EXPECT_FORWARDED_WATERMARKS_MARKER)) { this.expectForwardedWatermarks = true; } else if (element.getValue().equals(NO_FORWARDED_WATERMARKS_MARKER)) { this.expectForwardedWatermarks = false; } else { handleElement(element); } } @Override public void processWatermark(Watermark mark) throws Exception { if (!expectForwardedWatermarks) { throw new Exception("Received a " + mark + ", but this operator should not be forwarded watermarks."); } else { handleWatermark(mark); } } protected void handleElement(StreamRecord<String> element) { // do nothing } protected void handleWatermark(Watermark mark) { output.emitWatermark(mark); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hive.hcatalog.pig; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.common.classification.InterfaceAudience; import org.apache.hadoop.hive.common.classification.InterfaceStability; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.security.Credentials; import org.apache.hive.hcatalog.common.HCatConstants; import org.apache.hive.hcatalog.common.HCatContext; import org.apache.hive.hcatalog.common.HCatException; import org.apache.hive.hcatalog.data.schema.HCatSchema; import org.apache.hive.hcatalog.mapreduce.HCatOutputFormat; import org.apache.hive.hcatalog.mapreduce.OutputJobInfo; import org.apache.pig.PigException; import org.apache.pig.ResourceSchema; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.util.ObjectSerializer; import org.apache.pig.impl.util.UDFContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HCatStorer. * */ @InterfaceAudience.Public @InterfaceStability.Evolving public class HCatStorer extends HCatBaseStorer { private static final Logger LOG = LoggerFactory.getLogger(HCatStorer.class); // Signature for wrapped storer, see comments in LoadFuncBasedInputDriver.initialize final public static String INNER_SIGNATURE = "hcatstorer.inner.signature"; final public static String INNER_SIGNATURE_PREFIX = "hcatstorer_inner_signature"; // A hash map which stores job credentials. The key is a signature passed by Pig, which is //unique to the store func and out file name (table, in our case). private static Map<String, Credentials> jobCredentials = new HashMap<String, Credentials>(); private final static Options validOptions = new Options(); static { try { populateValidOptions(); } catch(Throwable t) { LOG.error("Failed to build option list: ", t); throw new RuntimeException(t); } } private final static CommandLineParser parser = new GnuParser(); /** * @param optString may empty str (not null), in which case it's no-op */ public HCatStorer(String partSpecs, String pigSchema, String optString) throws Exception { super(partSpecs, pigSchema); String[] optsArr = optString.split(" "); CommandLine configuredOptions; try { configuredOptions = parser.parse(validOptions, optsArr); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "[-" + ON_OOR_VALUE_OPT + "]", validOptions ); throw e; } Properties udfProps = UDFContext.getUDFContext().getUDFProperties(this.getClass(), new String[]{sign}); //downstream code expects it to be set to a valid value udfProps.put(ON_OORA_VALUE_PROP, configuredOptions.getOptionValue(ON_OOR_VALUE_OPT, getDefaultValue().name())); if(LOG.isDebugEnabled()) { LOG.debug("setting " + configuredOptions.getOptionValue(ON_OOR_VALUE_OPT)); } isValidOOROption((String)udfProps.get(ON_OORA_VALUE_PROP)); } public HCatStorer(String partSpecs, String pigSchema) throws Exception { this(partSpecs, pigSchema, ""); } public HCatStorer(String partSpecs) throws Exception { this(partSpecs, null, ""); } public HCatStorer() throws Exception { this(null, null, ""); } @Override public OutputFormat getOutputFormat() throws IOException { return new HCatOutputFormat(); } /** * makes a list of all options that HCatStorer understands */ private static void populateValidOptions() { validOptions.addOption(ON_OOR_VALUE_OPT, true, "Controls how store operation handles Pig values which are out of range for the target column" + "in Hive table. Default is to throw an exception."); } /** * check that onOutOfRangeValue handling is configured properly * @throws FrontendException */ private static void isValidOOROption(String optVal) throws FrontendException { boolean found = false; for(OOR_VALUE_OPT_VALUES v : OOR_VALUE_OPT_VALUES.values()) { if(v.name().equalsIgnoreCase(optVal)) { found = true; break; } } if(!found) { throw new FrontendException("Unexpected value for '" + ON_OOR_VALUE_OPT + "' found: " + optVal); } } /** * @param location databaseName.tableName */ @Override public void setStoreLocation(String location, Job job) throws IOException { Configuration config = job.getConfiguration(); config.set(INNER_SIGNATURE, INNER_SIGNATURE_PREFIX + "_" + sign); Properties udfProps = UDFContext.getUDFContext().getUDFProperties( this.getClass(), new String[]{sign}); String[] userStr = location.split("\\."); if (udfProps.containsKey(HCatConstants.HCAT_PIG_STORER_LOCATION_SET)) { for (Enumeration<Object> emr = udfProps.keys(); emr.hasMoreElements(); ) { PigHCatUtil.getConfigFromUDFProperties(udfProps, config, emr.nextElement().toString()); } Credentials crd = jobCredentials.get(INNER_SIGNATURE_PREFIX + "_" + sign); if (crd != null) { job.getCredentials().addAll(crd); } } else { Job clone = Job.getInstance(job.getConfiguration()); OutputJobInfo outputJobInfo; if (userStr.length == 2) { outputJobInfo = OutputJobInfo.create(userStr[0], userStr[1], partitions); } else if (userStr.length == 1) { outputJobInfo = OutputJobInfo.create(null, userStr[0], partitions); } else { throw new FrontendException("location " + location + " is invalid. It must be of the form [db.]table", PigHCatUtil.PIG_EXCEPTION_CODE); } Schema schema = (Schema) ObjectSerializer.deserialize(udfProps.getProperty(PIG_SCHEMA)); if (schema != null) { pigSchema = schema; } if (pigSchema == null) { throw new FrontendException( "Schema for data cannot be determined.", PigHCatUtil.PIG_EXCEPTION_CODE); } String externalLocation = (String) udfProps.getProperty(HCatConstants.HCAT_PIG_STORER_EXTERNAL_LOCATION); if (externalLocation != null) { outputJobInfo.setLocation(externalLocation); } try { HCatOutputFormat.setOutput(job, outputJobInfo); } catch (HCatException he) { // pass the message to the user - essentially something about // the table // information passed to HCatOutputFormat was not right throw new PigException(he.getMessage(), PigHCatUtil.PIG_EXCEPTION_CODE, he); } HCatSchema hcatTblSchema = HCatOutputFormat.getTableSchema(job.getConfiguration()); try { doSchemaValidations(pigSchema, hcatTblSchema); } catch (HCatException he) { throw new FrontendException(he.getMessage(), PigHCatUtil.PIG_EXCEPTION_CODE, he); } computedSchema = convertPigSchemaToHCatSchema(pigSchema, hcatTblSchema); HCatOutputFormat.setSchema(job, computedSchema); udfProps.setProperty(COMPUTED_OUTPUT_SCHEMA, ObjectSerializer.serialize(computedSchema)); // We will store all the new /changed properties in the job in the // udf context, so the the HCatOutputFormat.setOutput and setSchema // methods need not be called many times. for (Entry<String, String> keyValue : job.getConfiguration()) { String oldValue = clone.getConfiguration().getRaw(keyValue.getKey()); if ((oldValue == null) || (keyValue.getValue().equals(oldValue) == false)) { udfProps.put(keyValue.getKey(), keyValue.getValue()); } } //Store credentials in a private hash map and not the udf context to // make sure they are not public. jobCredentials.put(INNER_SIGNATURE_PREFIX + "_" + sign, job.getCredentials()); udfProps.put(HCatConstants.HCAT_PIG_STORER_LOCATION_SET, true); } } @Override public void storeSchema(ResourceSchema schema, String arg1, Job job) throws IOException { ShimLoader.getHadoopShims().getHCatShim().commitJob(getOutputFormat(), job); } @Override public void cleanupOnFailure(String location, Job job) throws IOException { ShimLoader.getHadoopShims().getHCatShim().abortJob(getOutputFormat(), job); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.exec; import static org.apache.hadoop.hive.serde.serdeConstants.STRING_TYPE_NAME; import java.io.OutputStream; import java.io.PrintStream; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.common.jsonexplain.JsonParser; import org.apache.hadoop.hive.common.jsonexplain.JsonParserFactory; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.ql.Driver; import org.apache.hadoop.hive.ql.DriverContext; import org.apache.hadoop.hive.ql.hooks.ReadEntity; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.optimizer.physical.StageIDsRearranger; import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer; import org.apache.hadoop.hive.ql.plan.Explain; import org.apache.hadoop.hive.ql.plan.Explain.Level; import org.apache.hadoop.hive.ql.plan.ExplainWork; import org.apache.hadoop.hive.ql.plan.HiveOperation; import org.apache.hadoop.hive.ql.plan.OperatorDesc; import org.apache.hadoop.hive.ql.plan.SparkWork; import org.apache.hadoop.hive.ql.plan.TezWork; import org.apache.hadoop.hive.ql.plan.api.StageType; import org.apache.hadoop.hive.ql.security.authorization.AuthorizationFactory; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.util.StringUtils; import org.apache.hive.common.util.AnnotationUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ExplainTask implementation. * **/ public class ExplainTask extends Task<ExplainWork> implements Serializable { private static final long serialVersionUID = 1L; public static final String EXPL_COLUMN_NAME = "Explain"; private final Set<Operator<?>> visitedOps = new HashSet<Operator<?>>(); private boolean isLogical = false; protected final Logger LOG; public ExplainTask() { super(); LOG = LoggerFactory.getLogger(this.getClass().getName()); } /* * Below method returns the dependencies for the passed in query to EXPLAIN. * The dependencies are the set of input tables and partitions, and are * provided back as JSON output for the EXPLAIN command. * Example output: * {"input_tables":[{"tablename": "default@test_sambavi_v1", "tabletype": "TABLE"}], * "input partitions":["default@srcpart@ds=2008-04-08/hr=11"]} */ private static JSONObject getJSONDependencies(ExplainWork work) throws Exception { assert(work.getDependency()); JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); List<Map<String, String>> inputTableInfo = new ArrayList<Map<String, String>>(); List<Map<String, String>> inputPartitionInfo = new ArrayList<Map<String, String>>(); for (ReadEntity input: work.getInputs()) { switch (input.getType()) { case TABLE: Table table = input.getTable(); Map<String, String> tableInfo = new LinkedHashMap<String, String>(); tableInfo.put("tablename", table.getCompleteName()); tableInfo.put("tabletype", table.getTableType().toString()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { tableInfo.put("tableParents", input.getParents().toString()); } inputTableInfo.add(tableInfo); break; case PARTITION: Map<String, String> partitionInfo = new HashMap<String, String>(); partitionInfo.put("partitionName", input.getPartition().getCompleteName()); if ((input.getParents() != null) && (!input.getParents().isEmpty())) { partitionInfo.put("partitionParents", input.getParents().toString()); } inputPartitionInfo.add(partitionInfo); break; default: break; } } outJSONObject.put("input_tables", inputTableInfo); outJSONObject.put("input_partitions", inputPartitionInfo); return outJSONObject; } public JSONObject getJSONLogicalPlan(PrintStream out, ExplainWork work) throws Exception { isLogical = true; JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); boolean jsonOutput = work.isFormatted(); if (jsonOutput) { out = null; } if (work.getParseContext() != null) { if (out != null) { out.print("LOGICAL PLAN:"); } JSONObject jsonPlan = outputMap(work.getParseContext().getTopOps(), true, out, jsonOutput, work.getExtended(), 0); if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("LOGICAL PLAN", jsonPlan); } } else { System.err.println("No parse context!"); } return outJSONObject; } public JSONObject getJSONPlan(PrintStream out, ExplainWork work) throws Exception { return getJSONPlan(out, work.getRootTasks(), work.getFetchTask(), work.isFormatted(), work.getExtended(), work.isAppendTaskType()); } public JSONObject getJSONPlan(PrintStream out, List<Task<?>> tasks, Task<?> fetchTask, boolean jsonOutput, boolean isExtended, boolean appendTaskType) throws Exception { // If the user asked for a formatted output, dump the json output // in the output stream JSONObject outJSONObject = new JSONObject(new LinkedHashMap<>()); if (jsonOutput) { out = null; } List<Task> ordered = StageIDsRearranger.getExplainOrder(conf, tasks); if (fetchTask != null) { fetchTask.setParentTasks((List)StageIDsRearranger.getFetchSources(tasks)); if (fetchTask.getNumParent() == 0) { fetchTask.setRootTask(true); } ordered.add(fetchTask); } JSONObject jsonDependencies = outputDependencies(out, jsonOutput, appendTaskType, ordered); if (out != null) { out.println(); } if (jsonOutput) { outJSONObject.put("STAGE DEPENDENCIES", jsonDependencies); } // Go over all the tasks and dump out the plans JSONObject jsonPlan = outputStagePlans(out, ordered, jsonOutput, isExtended); if (jsonOutput) { outJSONObject.put("STAGE PLANS", jsonPlan); } if (fetchTask != null) { fetchTask.setParentTasks(null); } return jsonOutput ? outJSONObject : null; } private List<String> toString(Collection<?> objects) { List<String> list = new ArrayList<String>(); for (Object object : objects) { list.add(String.valueOf(object)); } return list; } private Object toJson(String header, String message, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return message; } out.print(header); out.println(": "); out.print(indentString(2)); out.println(message); return null; } private Object toJson(String header, List<String> messages, PrintStream out, ExplainWork work) throws Exception { if (work.isFormatted()) { return new JSONArray(messages); } out.print(header); out.println(": "); for (String message : messages) { out.print(indentString(2)); out.print(message); out.println(); } return null; } @Override public int execute(DriverContext driverContext) { PrintStream out = null; try { Path resFile = work.getResFile(); OutputStream outS = resFile.getFileSystem(conf).create(resFile); out = new PrintStream(outS); if (work.isLogical()) { JSONObject jsonLogicalPlan = getJSONLogicalPlan(out, work); if (work.isFormatted()) { out.print(jsonLogicalPlan); } } else if (work.isAuthorize()) { JSONObject jsonAuth = collectAuthRelatedEntities(out, work); if (work.isFormatted()) { out.print(jsonAuth); } } else if (work.getDependency()) { JSONObject jsonDependencies = getJSONDependencies(work); out.print(jsonDependencies); } else { if (work.isUserLevelExplain()) { // Because of the implementation of the JsonParserFactory, we are sure // that we can get a TezJsonParser. JsonParser jsonParser = JsonParserFactory.getParser(conf); work.setFormatted(true); JSONObject jsonPlan = getJSONPlan(out, work); if (work.getCboInfo() != null) { jsonPlan.put("cboInfo", work.getCboInfo()); } try { jsonParser.print(jsonPlan, out); } catch (Exception e) { // if there is anything wrong happen, we bail out. LOG.error("Running explain user level has problem: " + e.toString() + ". Falling back to normal explain"); work.setFormatted(false); work.setUserLevelExplain(false); jsonPlan = getJSONPlan(out, work); } } else { JSONObject jsonPlan = getJSONPlan(out, work); if (work.isFormatted()) { out.print(jsonPlan); } } } out.close(); out = null; return (0); } catch (Exception e) { console.printError("Failed with exception " + e.getMessage(), "\n" + StringUtils.stringifyException(e)); return (1); } finally { IOUtils.closeStream(out); } } private JSONObject collectAuthRelatedEntities(PrintStream out, ExplainWork work) throws Exception { BaseSemanticAnalyzer analyzer = work.getAnalyzer(); HiveOperation operation = queryState.getHiveOperation(); JSONObject object = new JSONObject(new LinkedHashMap<>()); Object jsonInput = toJson("INPUTS", toString(analyzer.getInputs()), out, work); if (work.isFormatted()) { object.put("INPUTS", jsonInput); } Object jsonOutput = toJson("OUTPUTS", toString(analyzer.getOutputs()), out, work); if (work.isFormatted()) { object.put("OUTPUTS", jsonOutput); } String userName = SessionState.get().getAuthenticator().getUserName(); Object jsonUser = toJson("CURRENT_USER", userName, out, work); if (work.isFormatted()) { object.put("CURRENT_USER", jsonUser); } Object jsonOperation = toJson("OPERATION", operation.name(), out, work); if (work.isFormatted()) { object.put("OPERATION", jsonOperation); } if (analyzer.skipAuthorization()) { return object; } final List<String> exceptions = new ArrayList<String>(); Object delegate = SessionState.get().getActiveAuthorizer(); if (delegate != null) { Class itface = SessionState.get().getAuthorizerInterface(); Object authorizer = AuthorizationFactory.create(delegate, itface, new AuthorizationFactory.AuthorizationExceptionHandler() { public void exception(Exception exception) { exceptions.add(exception.getMessage()); } }); SessionState.get().setActiveAuthorizer(authorizer); try { Driver.doAuthorization(queryState.getHiveOperation(), analyzer, ""); } finally { SessionState.get().setActiveAuthorizer(delegate); } } if (!exceptions.isEmpty()) { Object jsonFails = toJson("AUTHORIZATION_FAILURES", exceptions, out, work); if (work.isFormatted()) { object.put("AUTHORIZATION_FAILURES", jsonFails); } } return object; } private static String indentString(int indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indent; ++i) { sb.append(" "); } return sb.toString(); } private JSONObject outputMap(Map<?, ?> mp, boolean hasHeader, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { TreeMap<Object, Object> tree = new TreeMap<Object, Object>(); tree.putAll(mp); JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null && hasHeader && !mp.isEmpty()) { out.println(); } for (Entry<?, ?> ent : tree.entrySet()) { // Print the key if (out != null) { out.print(indentString(indent)); out.print(ent.getKey()); out.print(" "); } // Print the value if (isPrintable(ent.getValue())) { if (out != null) { out.print(ent.getValue()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } else if (ent.getValue() instanceof List) { if (ent.getValue() != null && !((List<?>)ent.getValue()).isEmpty() && ((List<?>)ent.getValue()).get(0) != null && ((List<?>)ent.getValue()).get(0) instanceof TezWork.Dependency) { if (out != null) { boolean isFirst = true; for (TezWork.Dependency dep: (List<TezWork.Dependency>)ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getType()); out.print(")"); } out.println(); } if (jsonOutput) { for (TezWork.Dependency dep: (List<TezWork.Dependency>)ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getType()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else if (ent.getValue() != null && !((List<?>) ent.getValue()).isEmpty() && ((List<?>) ent.getValue()).get(0) != null && ((List<?>) ent.getValue()).get(0) instanceof SparkWork.Dependency) { if (out != null) { boolean isFirst = true; for (SparkWork.Dependency dep: (List<SparkWork.Dependency>) ent.getValue()) { if (!isFirst) { out.print(", "); } else { out.print("<- "); isFirst = false; } out.print(dep.getName()); out.print(" ("); out.print(dep.getShuffleType()); out.print(", "); out.print(dep.getNumPartitions()); out.print(")"); } out.println(); } if (jsonOutput) { for (SparkWork.Dependency dep: (List<SparkWork.Dependency>) ent.getValue()) { JSONObject jsonDep = new JSONObject(new LinkedHashMap<>()); jsonDep.put("parent", dep.getName()); jsonDep.put("type", dep.getShuffleType()); jsonDep.put("partitions", dep.getNumPartitions()); json.accumulate(ent.getKey().toString(), jsonDep); } } } else { if (out != null) { out.print(ent.getValue().toString()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } } else if (ent.getValue() instanceof Map) { if (out != null) { out.print(ent.getValue().toString()); out.println(); } if (jsonOutput) { json.put(ent.getKey().toString(), ent.getValue().toString()); } } else if (ent.getValue() != null) { if (out != null) { out.println(); } JSONObject jsonOut = outputPlan(ent.getValue(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (jsonOutput) { json.put(ent.getKey().toString(), jsonOut); } } else { if (out != null) { out.println(); } } } return jsonOutput ? json : null; } private JSONArray outputList(List<?> l, PrintStream out, boolean hasHeader, boolean extended, boolean jsonOutput, int indent) throws Exception { boolean first_el = true; boolean nl = false; JSONArray outputArray = new JSONArray(); for (Object o : l) { if (isPrintable(o)) { String delim = first_el ? " " : ", "; if (out != null) { out.print(delim); out.print(o); } if (jsonOutput) { outputArray.put(o); } nl = true; } else { if (first_el && (out != null) && hasHeader) { out.println(); } JSONObject jsonOut = outputPlan(o, out, extended, jsonOutput, jsonOutput ? 0 : (hasHeader ? indent + 2 : indent)); if (jsonOutput) { outputArray.put(jsonOut); } } first_el = false; } if (nl && (out != null)) { out.println(); } return jsonOutput ? outputArray : null; } private boolean isPrintable(Object val) { if (val instanceof Boolean || val instanceof String || val instanceof Integer || val instanceof Long || val instanceof Byte || val instanceof Float || val instanceof Double || val instanceof Path) { return true; } if (val != null && val.getClass().isPrimitive()) { return true; } return false; } private JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent) throws Exception { return outputPlan(work, out, extended, jsonOutput, indent, ""); } private JSONObject outputPlan(Object work, PrintStream out, boolean extended, boolean jsonOutput, int indent, String appendToHeader) throws Exception { // Check if work has an explain annotation Annotation note = AnnotationUtils.getAnnotation(work.getClass(), Explain.class); String keyJSONObject = null; if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()); } } if (invokeFlag) { keyJSONObject = xpl_note.displayName(); if (out != null) { out.print(indentString(indent)); if (appendToHeader != null && !appendToHeader.isEmpty()) { out.println(xpl_note.displayName() + appendToHeader); } else { out.println(xpl_note.displayName()); } } } } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; // If this is an operator then we need to call the plan generation on the // conf and then the children if (work instanceof Operator) { Operator<? extends OperatorDesc> operator = (Operator<? extends OperatorDesc>) work; if (operator.getConf() != null) { String appender = isLogical ? " (" + operator.getOperatorId() + ")" : ""; JSONObject jsonOut = outputPlan(operator.getConf(), out, extended, jsonOutput, jsonOutput ? 0 : indent, appender); if (this.work != null && this.work.isUserLevelExplain()) { if (jsonOut != null && jsonOut.length() > 0) { ((JSONObject) jsonOut.get(JSONObject.getNames(jsonOut)[0])).put("OperatorId:", operator.getOperatorId()); } } if (jsonOutput) { json = jsonOut; } } if (!visitedOps.contains(operator) || !isLogical) { visitedOps.add(operator); if (operator.getChildOperators() != null) { int cindent = jsonOutput ? 0 : indent + 2; for (Operator<? extends OperatorDesc> op : operator.getChildOperators()) { JSONObject jsonOut = outputPlan(op, out, extended, jsonOutput, cindent); if (jsonOutput) { ((JSONObject)json.get(JSONObject.getNames(json)[0])).accumulate("children", jsonOut); } } } } if (jsonOutput) { return json; } return null; } // We look at all methods that generate values for explain Method[] methods = work.getClass().getMethods(); Arrays.sort(methods, new MethodComparator()); for (Method m : methods) { int prop_indents = jsonOutput ? 0 : indent + 2; note = AnnotationUtils.getAnnotation(m, Explain.class); if (note instanceof Explain) { Explain xpl_note = (Explain) note; boolean invokeFlag = false; if (this.work != null && this.work.isUserLevelExplain()) { invokeFlag = Level.USER.in(xpl_note.explainLevels()); } else { if (extended) { invokeFlag = Level.EXTENDED.in(xpl_note.explainLevels()); } else { invokeFlag = Level.DEFAULT.in(xpl_note.explainLevels()); } } if (invokeFlag) { Object val = null; try { val = m.invoke(work); } catch (InvocationTargetException ex) { // Ignore the exception, this may be caused by external jars val = null; } if (val == null) { continue; } String header = null; boolean skipHeader = xpl_note.skipHeader(); boolean emptyHeader = false; if (!xpl_note.displayName().equals("")) { header = indentString(prop_indents) + xpl_note.displayName() + ":"; } else { emptyHeader = true; prop_indents = indent; header = indentString(prop_indents); } // Try the output as a primitive object if (isPrintable(val)) { if (out != null && shouldPrint(xpl_note, val)) { if (!skipHeader) { out.print(header); out.print(" "); } out.println(val); } if (jsonOutput && shouldPrint(xpl_note, val)) { json.put(header, val.toString()); } continue; } int ind = 0; if (!jsonOutput) { if (!skipHeader) { ind = prop_indents + 2; } else { ind = indent; } } // Try this as a map if (val instanceof Map) { // Go through the map and print out the stuff Map<?, ?> mp = (Map<?, ?>) val; if (out != null && !skipHeader && mp != null && !mp.isEmpty()) { out.print(header); } JSONObject jsonOut = outputMap(mp, !skipHeader && !emptyHeader, out, extended, jsonOutput, ind); if (jsonOutput && !mp.isEmpty()) { json.put(header, jsonOut); } continue; } // Try this as a list if (val instanceof List || val instanceof Set) { List l = val instanceof List ? (List)val : new ArrayList((Set)val); if (out != null && !skipHeader && l != null && !l.isEmpty()) { out.print(header); } JSONArray jsonOut = outputList(l, out, !skipHeader && !emptyHeader, extended, jsonOutput, ind); if (jsonOutput && !l.isEmpty()) { json.put(header, jsonOut); } continue; } // Finally check if it is serializable try { if (!skipHeader && out != null) { out.println(header); } JSONObject jsonOut = outputPlan(val, out, extended, jsonOutput, ind); if (jsonOutput && jsonOut != null && jsonOut.length() != 0) { if (!skipHeader) { json.put(header, jsonOut); } else { for(String k: JSONObject.getNames(jsonOut)) { json.put(k, jsonOut.get(k)); } } } continue; } catch (ClassCastException ce) { // Ignore } } } } if (jsonOutput) { if (keyJSONObject != null) { JSONObject ret = new JSONObject(new LinkedHashMap<>()); ret.put(keyJSONObject, json); return ret; } return json; } return null; } /** * use case: we want to print the object in explain only if it is true * how to do : print it unless the following 3 are all true: * 1. displayOnlyOnTrue tag is on * 2. object is boolean * 3. object is false * @param exp * @param val * @return */ private boolean shouldPrint(Explain exp, Object val) { if (exp.displayOnlyOnTrue() && (val instanceof Boolean) & !((Boolean)val)) { return false; } return true; } private JSONObject outputPlan(Task<?> task, PrintStream out, JSONObject parentJSON, boolean extended, boolean jsonOutput, int indent) throws Exception { if (out != null) { out.print(indentString(indent)); out.print("Stage: "); out.print(task.getId()); out.print("\n"); } // Start by getting the work part of the task and call the output plan for // the work JSONObject jsonOutputPlan = outputPlan(task.getWork(), out, extended, jsonOutput, jsonOutput ? 0 : indent + 2); if (out != null) { out.println(); } if (jsonOutput) { parentJSON.put(task.getId(), jsonOutputPlan); } return null; } private JSONObject outputDependencies(Task<?> task, PrintStream out, JSONObject parentJson, boolean jsonOutput, boolean taskType, int indent) throws Exception { boolean first = true; JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; if (out != null) { out.print(indentString(indent)); out.print(task.getId()); } if ((task.getParentTasks() == null || task.getParentTasks().isEmpty())) { if (task.isRootTask()) { if (out != null) { out.print(" is a root stage"); } if (jsonOutput) { json.put("ROOT STAGE", "TRUE"); } } } else { StringBuilder s = new StringBuilder(); first = true; for (Task<?> parent : task.getParentTasks()) { if (!first) { s.append(", "); } first = false; s.append(parent.getId()); } if (out != null) { out.print(" depends on stages: "); out.print(s.toString()); } if (jsonOutput) { json.put("DEPENDENT STAGES", s.toString()); } } Task<?> currBackupTask = task.getBackupTask(); if (currBackupTask != null) { if (out != null) { out.print(" has a backup stage: "); out.print(currBackupTask.getId()); } if (jsonOutput) { json.put("BACKUP STAGE", currBackupTask.getId()); } } if (task instanceof ConditionalTask && ((ConditionalTask) task).getListTasks() != null) { StringBuilder s = new StringBuilder(); first = true; for (Task<?> con : ((ConditionalTask) task).getListTasks()) { if (!first) { s.append(", "); } first = false; s.append(con.getId()); } if (out != null) { out.print(" , consists of "); out.print(s.toString()); } if (jsonOutput) { json.put("CONDITIONAL CHILD TASKS", s.toString()); } } if (taskType) { if (out != null) { out.print(" ["); out.print(task.getType()); out.print("]"); } if (jsonOutput) { json.put("TASK TYPE", task.getType().name()); } } if (out != null) { out.println(); } return jsonOutput ? json : null; } public String outputAST(String treeString, PrintStream out, boolean jsonOutput, int indent) throws JSONException { if (out != null) { out.print(indentString(indent)); out.println("ABSTRACT SYNTAX TREE:"); out.print(indentString(indent + 2)); out.println(treeString); } return jsonOutput ? treeString : null; } public JSONObject outputDependencies(PrintStream out, boolean jsonOutput, boolean appendTaskType, List<Task> tasks) throws Exception { if (out != null) { out.println("STAGE DEPENDENCIES:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { JSONObject jsonOut = outputDependencies(task, out, json, jsonOutput, appendTaskType, 2); if (jsonOutput && jsonOut != null) { json.put(task.getId(), jsonOut); } } return jsonOutput ? json : null; } public JSONObject outputStagePlans(PrintStream out, List<Task> tasks, boolean jsonOutput, boolean isExtended) throws Exception { if (out != null) { out.println("STAGE PLANS:"); } JSONObject json = jsonOutput ? new JSONObject(new LinkedHashMap<>()) : null; for (Task task : tasks) { outputPlan(task, out, json, isExtended, jsonOutput, 2); } return jsonOutput ? json : null; } /** * MethodComparator. * */ public class MethodComparator implements Comparator<Method> { @Override public int compare(Method m1, Method m2) { return m1.getName().compareTo(m2.getName()); } } @Override public StageType getType() { return StageType.EXPLAIN; } @Override public String getName() { return "EXPLAIN"; } public List<FieldSchema> getResultSchema() { FieldSchema tmpFieldSchema = new FieldSchema(); List<FieldSchema> colList = new ArrayList<FieldSchema>(); tmpFieldSchema.setName(EXPL_COLUMN_NAME); tmpFieldSchema.setType(STRING_TYPE_NAME); colList.add(tmpFieldSchema); return colList; } }
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dx.dex.code.form; import com.android.dx.dex.code.CstInsn; import com.android.dx.dex.code.DalvInsn; import com.android.dx.dex.code.InsnFormat; import com.android.dx.rop.code.RegisterSpec; import com.android.dx.rop.code.RegisterSpecList; import com.android.dx.rop.cst.Constant; import com.android.dx.rop.cst.CstMethodRef; import com.android.dx.rop.cst.CstType; import com.android.dx.rop.type.Type; import com.android.dx.util.AnnotatedOutput; import java.util.BitSet; /** * Instruction format {@code 35c}. See the instruction format spec * for details. */ public final class Form35c extends InsnFormat { /** {@code non-null;} unique instance of this class */ public static final InsnFormat THE_ONE = new Form35c(); /** Maximal number of operands */ private static final int MAX_NUM_OPS = 5; /** * Constructs an instance. This class is not publicly * instantiable. Use {@link #THE_ONE}. */ private Form35c() { // This space intentionally left blank. } /** {@inheritDoc} */ @Override public String insnArgString(DalvInsn insn) { RegisterSpecList regs = explicitize(insn.getRegisters()); return regListString(regs) + ", " + cstString(insn); } /** {@inheritDoc} */ @Override public String insnCommentString(DalvInsn insn, boolean noteIndices) { if (noteIndices) { return cstComment(insn); } else { return ""; } } /** {@inheritDoc} */ @Override public int codeSize() { return 3; } /** {@inheritDoc} */ @Override public boolean isCompatible(DalvInsn insn) { if (!(insn instanceof CstInsn)) { return false; } CstInsn ci = (CstInsn) insn; int cpi = ci.getIndex(); if (! unsignedFitsInShort(cpi)) { return false; } Constant cst = ci.getConstant(); if (!((cst instanceof CstMethodRef) || (cst instanceof CstType))) { return false; } RegisterSpecList regs = ci.getRegisters(); return (wordCount(regs) >= 0); } /** {@inheritDoc} */ @Override public BitSet compatibleRegs(DalvInsn insn) { RegisterSpecList regs = insn.getRegisters(); int sz = regs.size(); BitSet bits = new BitSet(sz); for (int i = 0; i < sz; i++) { RegisterSpec reg = regs.get(i); /* * The check below adds (category - 1) to the register, to * account for the fact that the second half of a * category-2 register has to be represented explicitly in * the result. */ bits.set(i, unsignedFitsInNibble(reg.getReg() + reg.getCategory() - 1)); } return bits; } /** {@inheritDoc} */ @Override public void writeTo(AnnotatedOutput out, DalvInsn insn) { int cpi = ((CstInsn) insn).getIndex(); RegisterSpecList regs = explicitize(insn.getRegisters()); int sz = regs.size(); int r0 = (sz > 0) ? regs.get(0).getReg() : 0; int r1 = (sz > 1) ? regs.get(1).getReg() : 0; int r2 = (sz > 2) ? regs.get(2).getReg() : 0; int r3 = (sz > 3) ? regs.get(3).getReg() : 0; int r4 = (sz > 4) ? regs.get(4).getReg() : 0; write(out, opcodeUnit(insn, makeByte(r4, sz)), // encode the fifth operand here (short) cpi, codeUnit(r0, r1, r2, r3)); } /** * Gets the number of words required for the given register list, where * category-2 values count as two words. Return {@code -1} if the * list requires more than five words or contains registers that need * more than a nibble to identify them. * * @param regs {@code non-null;} the register list in question * @return {@code >= -1;} the number of words required, or {@code -1} * if the list couldn't possibly fit in this format */ private static int wordCount(RegisterSpecList regs) { int sz = regs.size(); if (sz > MAX_NUM_OPS) { // It can't possibly fit. return -1; } int result = 0; for (int i = 0; i < sz; i++) { RegisterSpec one = regs.get(i); result += one.getCategory(); /* * The check below adds (category - 1) to the register, to * account for the fact that the second half of a * category-2 register has to be represented explicitly in * the result. */ if (!unsignedFitsInNibble(one.getReg() + one.getCategory() - 1)) { return -1; } } return (result <= MAX_NUM_OPS) ? result : -1; } /** * Returns a register list which is equivalent to the given one, * except that it splits category-2 registers into two explicit * entries. This returns the original list if no modification is * required * * @param orig {@code non-null;} the original list * @return {@code non-null;} the list with the described transformation */ private static RegisterSpecList explicitize(RegisterSpecList orig) { int wordCount = wordCount(orig); int sz = orig.size(); if (wordCount == sz) { return orig; } RegisterSpecList result = new RegisterSpecList(wordCount); int wordAt = 0; for (int i = 0; i < sz; i++) { RegisterSpec one = orig.get(i); result.set(wordAt, one); if (one.getCategory() == 2) { result.set(wordAt + 1, RegisterSpec.make(one.getReg() + 1, Type.VOID)); wordAt += 2; } else { wordAt++; } } result.setImmutable(); return result; } }
package com.silentgo.orm.base; import com.google.common.collect.Maps; import com.silentgo.orm.SilentGoOrm; import com.silentgo.orm.connect.ConnectManager; import com.silentgo.orm.infobuilder.BaseTableBuilder; import com.silentgo.orm.kit.DaoMethodKit; import com.silentgo.orm.kit.PropertyKit; import com.silentgo.orm.sqlparser.SQLKit; import com.silentgo.orm.sqlparser.daoresolve.DaoResolver; import com.silentgo.orm.sqlparser.daoresolve.DefaultDaoResolver; import com.silentgo.orm.sqlparser.methodnameparser.MethodParserKit; import com.silentgo.orm.sqltool.SqlResult; import com.silentgo.utils.ClassKit; import com.silentgo.utils.ConvertKit; import com.silentgo.utils.ReflectKit; import com.silentgo.utils.log.Log; import com.silentgo.utils.log.LogFactory; import com.silentgo.utils.reflect.SGClass; import com.silentgo.utils.reflect.SGMethod; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Project : silentgo * com.silentgo.core.plugin.db.bridge * * @author <a href="mailto:teddyzhu15@gmail.com" target="_blank">teddyzhu</a> * <p> * Created by teddyzhu on 16/9/22. */ public class DaoInterceptor implements MethodInterceptor { private static final Log LOGGER = LogFactory.get(); private static final Map<String, Class<? extends BaseDao>> cacheClz = new HashMap<>(); private static final Map<Method, List<String>> cacheNamePaser = new HashMap<>(); private static final ArrayList EmptyList = new ArrayList<>(); public static <T> T proxy(Class<T> tclz) { Enhancer en = new Enhancer(); en.setSuperclass(tclz); en.setCallback(new DaoInterceptor()); T tt = (T) en.create(); return tt; } private static final DefaultDaoResolver daoResolveFactory = new DefaultDaoResolver(); private static final Map<Method, SQLTool> sqlToolCache = new ConcurrentHashMap<>(); private static final Map<Class<?>, Map<Method, SQLTool>> baseDaoCacheSqlTool = new ConcurrentHashMap<>(); @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { Long start = System.currentTimeMillis(); DBConnect connect = null; DaoResolveEntity daoResolveEntity = buildDaoResolveEntity(o, method, objects); SQLTool cachedSqlTool = null; if (daoResolveEntity.isBaseDao()) { Map<Method, SQLTool> sqlToolMapCache = baseDaoCacheSqlTool.get(daoResolveEntity.getDaoClass()); if (sqlToolMapCache == null) { sqlToolMapCache = Maps.newConcurrentMap(); baseDaoCacheSqlTool.put(daoResolveEntity.getDaoClass(), sqlToolMapCache); } cachedSqlTool = sqlToolMapCache.get(method); } else { cachedSqlTool = sqlToolCache.get(method); } if (cachedSqlTool == null) { for (DaoResolver daoResolver : daoResolveFactory.getResolverList()) { if (daoResolver.handle(daoResolveEntity)) { daoResolver.processSQL(daoResolveEntity); } } if (daoResolveEntity.isBaseDao()) { baseDaoCacheSqlTool.get(daoResolveEntity.getDaoClass()).put(method, daoResolveEntity.getSqlTool()); } else { sqlToolCache.put(method, daoResolveEntity.getSqlTool()); } } else { cachedSqlTool.setObjects(daoResolveEntity.getObjects()); cachedSqlTool.setParams(daoResolveEntity.getNameObjects()); daoResolveEntity.setSqlTool(cachedSqlTool); } LOGGER.debug("dao parse sql end in {} ms", System.currentTimeMillis() - start); Object ret = null; BaseTableBuilder baseTableBuilder = BaseTableBuilder.me(); BaseTableInfo tableInfo = daoResolveEntity.getTableInfo(); Class<?> daoClass = daoResolveEntity.getDaoClass(); try { SqlResult sqlResult = daoResolveEntity.getSqlTool().getSQL(); SQLType type = daoResolveEntity.getSqlTool().getType(); Object[] args = sqlResult.getDy().toArray(); String sql = sqlResult.getSql().toString(); switch (type) { case QUERY: case COUNT: { DaoMethod daoMethod = getDaoMethod(method, daoClass, baseTableBuilder.getReflectMap().get(daoClass)); connect = ConnectManager.me().getConnect(tableInfo.getType(), tableInfo.getPoolName()); ret = excuteQuery(sql, args, connect, daoMethod); break; } case DELETE: case UPDATE: { connect = ConnectManager.me().getConnect(tableInfo.getType(), tableInfo.getPoolName()); ret = SilentGoOrm.updateOrDelete(connect, sql, type.name(), int.class, args); break; } case INSERT: { connect = ConnectManager.me().getConnect(tableInfo.getType(), tableInfo.getPoolName()); Object[] generateKeys; if (objects.length == 1) { if (objects[0] instanceof Collection) generateKeys = new Object[((Collection) objects[0]).size()]; else generateKeys = new Object[1]; } else { generateKeys = new Object[0]; } ret = SilentGoOrm.insert(connect, sql, int.class, generateKeys, args); resolveInsertResult(tableInfo, generateKeys, objects); break; } } LOGGER.debug("execute sql end"); } catch (Exception e) { LOGGER.error(e); throw e; } finally { if (connect != null && connect.getConnect().getAutoCommit()) { ConnectManager.me().releaseConnect(tableInfo.getType(), tableInfo.getPoolName(), connect); } daoResolveEntity.clearSqlTool(); } LOGGER.debug("end orm method : {}", System.currentTimeMillis() - start); return ret; } private DaoResolveEntity buildDaoResolveEntity(Object o, Method method, Object[] objects) { Long start = System.currentTimeMillis(); DaoResolveEntity daoResolveEntity = new DaoResolveEntity(); BaseTableBuilder baseTableBuilder = BaseTableBuilder.me(); SGClass sgClass = ReflectKit.getSGClass(method.getDeclaringClass()); SGMethod sgMethod = sgClass.getMethod(method); List<String> parsedString; List<Annotation> annotations = baseTableBuilder.getMethodListMap().getOrDefault(method, EmptyList); Class<? extends BaseDao> daoClass = (Class<? extends BaseDao>) method.getDeclaringClass(); if (BaseDao.class.equals(daoClass)) { daoResolveEntity.setBaseDao(true); daoClass = getClz(o.getClass().getName()); } else { daoResolveEntity.setBaseDao(false); } BaseTableInfo tableInfo = baseTableBuilder.getClassTableInfoMap().get(daoClass); BaseDaoDialect daoDialect = baseTableBuilder.getDialect(tableInfo.getType()); boolean cached = cacheNamePaser.containsKey(method); if (cached) { parsedString = cacheNamePaser.get(method); } else { parsedString = new ArrayList<>(); MethodParserKit.parse(sgMethod.getName(), annotations, parsedString, tableInfo); cacheNamePaser.put(method, parsedString); } LOGGER.debug("dao prepare for parse object , end in {} ms", System.currentTimeMillis() - start); Map<String, Object> namdObjects = new HashMap<>(); Object[] sequentialObject = SQLKit.parseNamedObject(sgMethod, objects, namdObjects); LOGGER.debug("dao parse object end in {} ms", System.currentTimeMillis() - start); daoResolveEntity.setHandled(false); daoResolveEntity.setSqlTool(new SQLTool()); daoResolveEntity.setDaoDialect(daoDialect); daoResolveEntity.setNameObjects(namdObjects); daoResolveEntity.setSgMethod(sgMethod); daoResolveEntity.setParsedMethod(parsedString); daoResolveEntity.setTableInfo(tableInfo); daoResolveEntity.setDaoClass(daoClass); daoResolveEntity.setObjects(sequentialObject); daoResolveEntity.setObjectIndex(0); daoResolveEntity.setObjectParsedIndex(0); daoResolveEntity.getSqlTool().setObjects(sequentialObject); daoResolveEntity.getSqlTool().setParams(namdObjects); return daoResolveEntity; } private Class<? extends BaseDao> getClz(String clzString) { int index = clzString.indexOf("$$EnhancerByCGLIB"); String clzStr = clzString.substring(0, index); Class<? extends BaseDao> clz = cacheClz.get(clzStr); if (clz == null) { try { clz = (Class<? extends BaseDao>) Class.forName(clzStr); cacheClz.put(clzStr, clz); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return clz; } private void resolveInsertResult(BaseTableInfo tableInfos, Object[] generateKeys, Object[] params) throws InvocationTargetException, IllegalAccessException { if (tableInfos.getPrimaryKeys().size() == 0) return; if (params.length == 1) { Map<String, PropertyDescriptor> propertyDescriptorMap = PropertyKit.getCachedProps(tableInfos); PropertyDescriptor p = propertyDescriptorMap.get(tableInfos.getPrimaryKeys().get(0)); if (params[0] instanceof Collection) { Collection objects = (Collection) params[0]; Iterator iterator = objects.iterator(); int i = 0; while (iterator.hasNext() && i < generateKeys.length) { p.getWriteMethod().invoke(iterator.next(), ConvertKit.getTypeConvert(String.class, p.getPropertyType()).convert(generateKeys[i].toString())); i++; } } else { p.getWriteMethod().invoke(params[0], ConvertKit.getTypeConvert(String.class, p.getPropertyType()).convert(generateKeys[0].toString())); } } } private Object excuteQuery(String sql, Object[] objects, DBConnect connect, DaoMethod daoMethod) throws SQLException { if (daoMethod.isList()) { if (daoMethod.isArray()) { return SilentGoOrm.queryArrayList(connect, sql, daoMethod.getType(), objects); } else { return SilentGoOrm.queryList(connect, sql, daoMethod.getType(), objects); } } else if (daoMethod.isArray()) { return SilentGoOrm.queryArray(connect, sql, daoMethod.getType(), objects); } else { return SilentGoOrm.query(connect, sql, daoMethod.getType(), objects); } } private DaoMethod getDaoMethod(Method method, Class<?> daoClass, Class<? extends TableModel> modelClass) { DaoMethod daoMethod = BaseDao.class.equals(method.getDeclaringClass()) ? null : DaoMethodKit.getDaoMethod(method); if (daoMethod == null) { daoMethod = new DaoMethod(); DaoMethodKit.addDaoMethod(method, daoMethod); if (method.getDeclaringClass().equals(daoClass)) { if (Collection.class.isAssignableFrom(method.getReturnType())) { daoMethod.setList(true); Class<?> retClz = ClassKit.getActualType(method.getGenericReturnType()); if (retClz.isArray()) daoMethod.setArray(true); daoMethod.setType(retClz); return daoMethod; } else if (method.getReturnType().isArray()) { daoMethod.setArray(true); daoMethod.setType(method.getReturnType().getComponentType()); return daoMethod; } else { daoMethod.setType(method.getReturnType()); return daoMethod; } } else { if (int.class.equals(method.getReturnType())) { daoMethod.setType(int.class); } else { daoMethod.setType(modelClass); } if (Collection.class.isAssignableFrom(method.getReturnType())) { daoMethod.setList(true); } return daoMethod; } } return daoMethod; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tez.runtime.library.common.sort.impl; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BoundedByteArrayOutputStream; import org.apache.hadoop.io.BufferUtils; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.io.serializer.Deserializer; import org.apache.hadoop.io.serializer.SerializationFactory; import org.apache.tez.runtime.library.common.InputAttemptIdentifier; import org.apache.tez.runtime.library.common.shuffle.impl.InMemoryReader; import org.apache.tez.runtime.library.common.shuffle.impl.InMemoryWriter; import org.apache.tez.runtime.library.common.sort.impl.IFile.Reader; import org.apache.tez.runtime.library.common.sort.impl.IFile.Writer; import org.apache.tez.runtime.library.testutils.KVDataGen; import org.apache.tez.runtime.library.testutils.KVDataGen.KVPair; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class TestIFile { private static final Log LOG = LogFactory.getLog(TestIFile.class); private static Configuration defaultConf = new Configuration(); private static FileSystem localFs = null; private static Path workDir = null; private static CompressionCodec codec; private Random rnd = new Random(); private String outputFileName = "ifile.out"; private Path outputPath; private DataOutputBuffer k = new DataOutputBuffer(); private DataOutputBuffer v = new DataOutputBuffer(); static { defaultConf.set("fs.defaultFS", "file:///"); try { localFs = FileSystem.getLocal(defaultConf); workDir = new Path( new Path(System.getProperty("test.build.data", "/tmp")), TestIFile.class.getName()) .makeQualified(localFs.getUri(), localFs.getWorkingDirectory()); LOG.info("Using workDir: " + workDir); } catch (IOException e) { throw new RuntimeException(e); } } @Before public void setUp() throws Exception { CompressionCodecFactory codecFactory = new CompressionCodecFactory(new Configuration()); codec = codecFactory.getCodecByClassName("org.apache.hadoop.io.compress.DefaultCodec"); outputPath = new Path(workDir, outputFileName); } @Before @After public void cleanup() throws Exception { localFs.delete(workDir, true); } @Test //empty IFile public void testWithEmptyIFile() throws IOException { testWriterAndReader(new LinkedList<KVPair>()); testWithDataBuffer(new LinkedList<KVPair>()); } @Test //Write empty key value pairs public void testWritingEmptyKeyValues() throws IOException { DataInputBuffer key = new DataInputBuffer(); DataInputBuffer value = new DataInputBuffer(); IFile.Writer writer = new IFile.Writer(defaultConf, localFs, outputPath, null, null, null, null, null); writer.append(key, value); writer.append(key, value); writer.append(key, value); writer.append(key, value); writer.close(); IFile.Reader reader = new Reader(localFs, outputPath, null, null, null, false, -1, 1024); DataInputBuffer keyIn = new DataInputBuffer(); DataInputBuffer valIn = new DataInputBuffer(); int records = 0; while (reader.nextRawKey(keyIn)) { reader.nextRawValue(valIn); records++; assert(keyIn.getLength() == 0); assert(valIn.getLength() == 0); } assertTrue("Number of records read does not match", (records == 4)); reader.close(); } @Test //test with unsorted data and repeat keys public void testWithUnsortedData() throws IOException { List<KVPair> unsortedData = KVDataGen.generateTestData(false, rnd.nextInt(100)); testWriterAndReader(unsortedData); testWithDataBuffer(unsortedData); } @Test //test with sorted data and repeat keys public void testWithSortedData() throws IOException { List<KVPair> sortedData = KVDataGen.generateTestData(true, rnd.nextInt(100)); testWriterAndReader(sortedData); testWithDataBuffer(sortedData); } @Test //test with sorted data and repeat keys public void testWithRLEMarker() throws IOException { //keys would be repeated exactly 2 times //e.g (k1,v1), (k1,v2), (k3, v3), (k4, v4), (k4, v5)... //This should trigger RLE marker in IFile. List<KVPair> sortedData = KVDataGen.generateTestData(true, 1); testWriterAndReader(sortedData); testWithDataBuffer(sortedData); List<KVPair> unsortedData = KVDataGen.generateTestData(false, 1); testWriterAndReader(sortedData); testWithDataBuffer(sortedData); } @Test //test with unique keys public void testWithUniqueKeys() throws IOException { //all keys are unique List<KVPair> sortedData = KVDataGen.generateTestData(true, 0); testWriterAndReader(sortedData); testWithDataBuffer(sortedData); } @Test //Test InMemoryWriter public void testInMemoryWriter() throws IOException { InMemoryWriter writer = null; BoundedByteArrayOutputStream bout = new BoundedByteArrayOutputStream(1024 * 1024); List<KVPair> data = KVDataGen.generateTestData(true, 0); //No RLE, No RepeatKeys, no compression writer = new InMemoryWriter(bout); writeTestFileUsingDataBuffer(writer, false, false, data, null); readUsingInMemoryReader(bout.getBuffer(), data); //No RLE, RepeatKeys, no compression bout.reset(); writer = new InMemoryWriter(bout); writeTestFileUsingDataBuffer(writer, false, true, data, null); readUsingInMemoryReader(bout.getBuffer(), data); //RLE, No RepeatKeys, no compression bout.reset(); writer = new InMemoryWriter(bout); writeTestFileUsingDataBuffer(writer, true, false, data, null); readUsingInMemoryReader(bout.getBuffer(), data); //RLE, RepeatKeys, no compression bout.reset(); writer = new InMemoryWriter(bout); writeTestFileUsingDataBuffer(writer, true, true, data, null); readUsingInMemoryReader(bout.getBuffer(), data); } @Test //Test appendValue feature public void testAppendValue() throws IOException { List<KVPair> data = KVDataGen.generateTestData(false, rnd.nextInt(100)); IFile.Writer writer = new IFile.Writer(defaultConf, localFs, outputPath, Text.class, IntWritable.class, codec, null, null); Text previousKey = null; for (KVPair kvp : data) { if ((previousKey != null && previousKey.compareTo(kvp.getKey()) == 0)) { writer.appendValue(kvp.getvalue()); } else { writer.append(kvp.getKey(), kvp.getvalue()); } previousKey = kvp.getKey(); } writer.close(); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); } @Test //Test appendValues feature public void testAppendValues() throws IOException { List<KVPair> data = new ArrayList<KVPair>(); List<IntWritable> values = new ArrayList<IntWritable>(); Text key = new Text("key"); IntWritable val = new IntWritable(1); for(int i = 0; i < 5; i++) { data.add(new KVPair(key, val)); values.add(val); } IFile.Writer writer = new IFile.Writer(defaultConf, localFs, outputPath, Text.class, IntWritable.class, codec, null, null); writer.append(data.get(0).getKey(), data.get(0).getvalue()); //write first KV pair writer.appendValues(values.subList(1, values.size()).iterator()); //add the rest here Text lastKey = new Text("key3"); IntWritable lastVal = new IntWritable(10); data.add(new KVPair(lastKey, lastVal)); writer.append(lastKey, lastVal); writer.close(); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); } @Test //Test appendKeyValues feature public void testAppendKeyValues() throws IOException { List<KVPair> data = new ArrayList<KVPair>(); List<IntWritable> values = new ArrayList<IntWritable>(); Text key = new Text("key"); IntWritable val = new IntWritable(1); for(int i = 0; i < 5; i++) { data.add(new KVPair(key, val)); values.add(val); } IFile.Writer writer = new IFile.Writer(defaultConf, localFs, outputPath, Text.class, IntWritable.class, codec, null, null); writer.appendKeyValues(data.get(0).getKey(), values.iterator()); Text lastKey = new Text("key3"); IntWritable lastVal = new IntWritable(10); data.add(new KVPair(lastKey, lastVal)); writer.append(lastKey, lastVal); writer.close(); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); } @Test //Test appendValue with DataInputBuffer public void testAppendValueWithDataInputBuffer() throws IOException { List<KVPair> data = KVDataGen.generateTestData(false, rnd.nextInt(100)); IFile.Writer writer = new IFile.Writer(defaultConf, localFs, outputPath, Text.class, IntWritable.class, codec, null, null); final DataInputBuffer previousKey = new DataInputBuffer(); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer value = new DataInputBuffer(); for (KVPair kvp : data) { populateData(kvp, key, value); if ((previousKey != null && BufferUtils.compare(key, previousKey) == 0)) { writer.appendValue(value); } else { writer.append(key, value); } previousKey.reset(k.getData(), 0, k.getLength()); } writer.close(); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); } /** * Test different options (RLE, repeat keys, compression) on reader/writer * * @param data * @throws IOException */ private void testWriterAndReader(List<KVPair> data) throws IOException { Writer writer = null; //No RLE, No RepeatKeys writer = writeTestFile(false, false, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFile(false, false, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); //No RLE, RepeatKeys writer = writeTestFile(false, true, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFile(false, true, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); //RLE, No RepeatKeys writer = writeTestFile(true, false, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFile(true, false, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); //RLE, RepeatKeys writer = writeTestFile(true, true, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFile(true, true, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); } /** * Test different options (RLE, repeat keys, compression) on reader/writer * * @param data * @throws IOException */ private void testWithDataBuffer(List<KVPair> data) throws IOException { Writer writer = null; //No RLE, No RepeatKeys writer = writeTestFileUsingDataBuffer(false, false, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFileUsingDataBuffer(false, false, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); //No RLE, RepeatKeys writer = writeTestFileUsingDataBuffer(false, true, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFileUsingDataBuffer(false, true, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); //RLE, No RepeatKeys writer = writeTestFileUsingDataBuffer(true, false, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFileUsingDataBuffer(true, false, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); //RLE, RepeatKeys writer = writeTestFileUsingDataBuffer(true, true, data, null); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, null); writer = writeTestFileUsingDataBuffer(true, true, data, codec); readAndVerifyData(writer.getRawLength(), writer.getCompressedLength(), data, codec); } private void readAndVerifyData(long rawLength, long compressedLength, List<KVPair> originalData, CompressionCodec codec) throws IOException { readFileUsingInMemoryReader(rawLength, compressedLength, originalData); readUsingIFileReader(originalData, codec); } /** * Read data using in memory reader * * @param rawLength * @param compressedLength * @param originalData * @throws IOException */ private void readFileUsingInMemoryReader(long rawLength, long compressedLength, List<KVPair> originalData) throws IOException { LOG.info("Read using in memory reader"); FSDataInputStream inStream = localFs.open(outputPath); byte[] bytes = new byte[(int) rawLength]; IFile.Reader.readToMemory(bytes, inStream, (int) compressedLength, codec, false, -1); inStream.close(); readUsingInMemoryReader(bytes, originalData); } private void readUsingInMemoryReader(byte[] bytes, List<KVPair> originalData) throws IOException { InMemoryReader inMemReader = new InMemoryReader(null, new InputAttemptIdentifier(0, 0), bytes, 0, bytes.length); verifyData(inMemReader, originalData); } /** * Read data using IFile Reader * * @param originalData * @param codec * @throws IOException */ private void readUsingIFileReader(List<KVPair> originalData, CompressionCodec codec) throws IOException { LOG.info("Read using IFile reader"); IFile.Reader reader = new IFile.Reader(localFs, outputPath, codec, null, null, false, 0, -1); verifyData(reader, originalData); reader.close(); } /** * Data verification * * @param reader * @param data * @throws IOException */ private void verifyData(Reader reader, List<KVPair> data) throws IOException { LOG.info("Data verification"); Text readKey = new Text(); IntWritable readValue = new IntWritable(); DataInputBuffer keyIn = new DataInputBuffer(); DataInputBuffer valIn = new DataInputBuffer(); Deserializer<Text> keyDeserializer; Deserializer<IntWritable> valDeserializer; SerializationFactory serializationFactory = new SerializationFactory( defaultConf); keyDeserializer = serializationFactory.getDeserializer(Text.class); valDeserializer = serializationFactory.getDeserializer(IntWritable.class); keyDeserializer.open(keyIn); valDeserializer.open(valIn); int numRecordsRead = 0; while (reader.nextRawKey(keyIn)) { reader.nextRawValue(valIn); readKey = keyDeserializer.deserialize(readKey); readValue = valDeserializer.deserialize(readValue); KVPair expected = data.get(numRecordsRead); assertEquals("Key does not match: Expected: " + expected.getKey() + ", Read: " + readKey, expected.getKey(), readKey); assertEquals("Value does not match: Expected: " + expected.getvalue() + ", Read: " + readValue, expected.getvalue(), readValue); numRecordsRead++; } assertEquals("Expected: " + data.size() + " records, but found: " + numRecordsRead, data.size(), numRecordsRead); LOG.info("Found: " + numRecordsRead + " records"); } private Writer writeTestFile(boolean rle, boolean repeatKeys, List<KVPair> data, CompressionCodec codec) throws IOException { FSDataOutputStream out = localFs.create(outputPath); IFile.Writer writer = new IFile.Writer(defaultConf, out, Text.class, IntWritable.class, codec, null, null, rle); writeTestFile(writer, rle, repeatKeys, data, codec); out.close(); return writer; } private Writer writeTestFile(IFile.Writer writer, boolean rle, boolean repeatKeys, List<KVPair> data, CompressionCodec codec) throws IOException { assertNotNull(writer); Text previousKey = null; for (KVPair kvp : data) { if (repeatKeys && (previousKey != null && previousKey.compareTo(kvp.getKey()) == 0)) { //RLE is enabled in IFile when IFile.REPEAT_KEY is set writer.append(IFile.REPEAT_KEY, kvp.getvalue()); } else { writer.append(kvp.getKey(), kvp.getvalue()); } previousKey = kvp.getKey(); } writer.close(); LOG.info("Uncompressed: " + writer.getRawLength()); LOG.info("CompressedSize: " + writer.getCompressedLength()); return writer; } private Writer writeTestFileUsingDataBuffer(boolean rle, boolean repeatKeys, List<KVPair> data, CompressionCodec codec) throws IOException { FSDataOutputStream out = localFs.create(outputPath); IFile.Writer writer = new IFile.Writer(defaultConf, out, Text.class, IntWritable.class, codec, null, null, rle); writeTestFileUsingDataBuffer(writer, rle, repeatKeys, data, codec); out.close(); return writer; } private Writer writeTestFileUsingDataBuffer(IFile.Writer writer, boolean rle, boolean repeatKeys, List<KVPair> data, CompressionCodec codec) throws IOException { DataInputBuffer previousKey = new DataInputBuffer(); DataInputBuffer key = new DataInputBuffer(); DataInputBuffer value = new DataInputBuffer(); for (KVPair kvp : data) { populateData(kvp, key, value); if (repeatKeys && (previousKey != null && BufferUtils.compare(key, previousKey) == 0)) { writer.append(IFile.REPEAT_KEY, value); } else { writer.append(key, value); } previousKey.reset(k.getData(), 0, k.getLength()); } writer.close(); LOG.info("Uncompressed: " + writer.getRawLength()); LOG.info("CompressedSize: " + writer.getCompressedLength()); return writer; } private void populateData(KVPair kvp, DataInputBuffer key, DataInputBuffer value) throws IOException { DataOutputBuffer k = new DataOutputBuffer(); DataOutputBuffer v = new DataOutputBuffer(); kvp.getKey().write(k); kvp.getvalue().write(v); key.reset(k.getData(), 0, k.getLength()); value.reset(v.getData(), 0, v.getLength()); } }
package org.cytoscape.rest.internal.resource; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.cytoscape.io.write.CyWriter; import org.cytoscape.io.write.VizmapWriterFactory; import org.cytoscape.rest.internal.CyActivator.WriterListener; import org.cytoscape.rest.internal.MappingFactoryManager; import org.cytoscape.rest.internal.datamapper.VisualStyleMapper; import org.cytoscape.rest.internal.serializer.VisualStyleModule; import org.cytoscape.rest.internal.serializer.VisualStyleSerializer; import org.cytoscape.rest.internal.task.HeadlessTaskMonitor; import org.cytoscape.view.model.DiscreteRange; import org.cytoscape.view.model.Range; import org.cytoscape.view.model.VisualLexicon; import org.cytoscape.view.model.VisualProperty; import org.cytoscape.view.vizmap.VisualMappingFunction; import org.cytoscape.view.vizmap.VisualPropertyDependency; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.view.vizmap.VisualStyleFactory; import org.cytoscape.work.TaskMonitor; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @Singleton @Path("/v1/styles") public class StyleResource extends AbstractResource { private final VisualStyleSerializer styleSerializer = new VisualStyleSerializer(); @Context private WriterListener writerListener; @Context private TaskMonitor tm; @Context private VisualStyleFactory vsFactory; @Context private MappingFactoryManager factoryManager; private final ObjectMapper styleMapper; private final VisualStyleMapper visualStyleMapper; private final VisualStyleSerializer visualStyleSerializer; public StyleResource() { super(); this.styleMapper = new ObjectMapper(); this.styleMapper.registerModule(new VisualStyleModule()); this.visualStyleMapper = new VisualStyleMapper(); this.visualStyleSerializer = new VisualStyleSerializer(); } /** * * @summary Get list of Visual Style titles * * @return List of Visual Style titles. */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) public String getStyleNames() { final Collection<VisualStyle> styles = vmm.getAllVisualStyles(); final List<String> styleNames = new ArrayList<String>(); for (final VisualStyle style : styles) { styleNames.add(style.getTitle()); } try { return getNames(styleNames); } catch (IOException e) { throw getError("Could not get style names.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * @summary Get number of Visual Styles * * @return Number of Visual Styles available in current session. * */ @GET @Path("/count") @Produces(MediaType.APPLICATION_JSON) public String getStylCount() { return getNumberObjectString(JsonTags.COUNT, vmm.getAllVisualStyles().size()); } /** * * @summary Delete a Visual Style * * @param name */ @DELETE @Path("/{name}") @Produces(MediaType.APPLICATION_JSON) public Response deleteStyle(@PathParam("name") String name) { vmm.removeVisualStyle(getStyleByName(name)); return Response.ok().build(); } /** * @summary Delete all Visual Styles except default style * */ @DELETE @Path("/") @Produces(MediaType.APPLICATION_JSON) public Response deleteAllStyles() { Set<VisualStyle> styles = vmm.getAllVisualStyles(); Set<VisualStyle> toBeDeleted = new HashSet<VisualStyle>(); for(final VisualStyle style: styles) { if(style.getTitle().equals("default") == false) { toBeDeleted.add(style); } } toBeDeleted.stream() .forEach(style->vmm.removeVisualStyle(style)); return Response.ok().build(); } /** * * @summary Delete a Visual Mapping from a Visual Style * * @param name Name of the Visual Style * @param vpName Visual Property name associated with the mapping * */ @DELETE @Path("/{name}/mappings/{vpName}") @Produces(MediaType.APPLICATION_JSON) public Response deleteMapping(@PathParam("name") String name, @PathParam("vpName") String vpName) { final VisualStyle style = getStyleByName(name); final VisualProperty<?> vp = getVisualProperty(vpName); if(vp == null) { throw new NotFoundException("Could not find Visual Property: " + vpName); } final VisualMappingFunction<?,?> mapping = style.getVisualMappingFunction(vp); if(mapping == null) { throw new NotFoundException("Could not find mapping for: " + vpName); } style.removeVisualMappingFunction(vp); return Response.ok().build(); } /** * * @summary Get all default values for the Visual Style * * @param name Name of the Visual Style * * @return List of all default values * */ @GET @Path("/{name}/defaults") @Produces(MediaType.APPLICATION_JSON) public String getDefaults(@PathParam("name") String name) { return serializeDefaultValues(name); } /** * * @summary Get a default value for the Visual Property * * @param name Name of Visual Style * @param vp Unique ID of the Visual Property. This should be the unique ID of the VP. * * @return Default value for the Visual Property * */ @GET @Path("/{name}/defaults/{vp}") @Produces(MediaType.APPLICATION_JSON) public String getDefaultValue(@PathParam("name") String name, @PathParam("vp") String vp) { return serializeDefaultValue(name, vp); } /** * This method is only for Visual Properties with DiscreteRange, such as * NODE_SHAPE or EDGE_LINE_TYPE. * * @summary Get all available range values for the Visual Property * * @param vp Visual Property ID * * @return List of all available values for the visual property. */ @GET @Path("/visualproperties/{vp}/values") @Produces(MediaType.APPLICATION_JSON) public String getRangeValues(@PathParam("vp") String vp) { return serializeRangeValue(vp); } /** * @summary Get all available Visual Properties * * @return Array of Visual Properties * */ @GET @Path("/visualproperties") @Produces(MediaType.APPLICATION_JSON) public String getVisualProperties() { final Set<VisualProperty<?>> vps = getAllVisualProperties(); try { return styleSerializer.serializeVisualProperties(vps); } catch (IOException e) { e.printStackTrace(); throw getError("Could not serialize Visual Properties.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * @summary Get a Visual Property * * @param visualProperty Target Visual Property ID * * @return Visual Property as object */ @GET @Path("/visualproperties/{visualProperty}") @Produces(MediaType.APPLICATION_JSON) public String getSingleVisualProperty(@PathParam("visualProperty") String visualProperty) { final VisualProperty<?> vp = getVisualProperty(visualProperty); try { return styleSerializer.serializeVisualProperty(vp); } catch (IOException e) { throw getError("Could not serialize Visual Properties.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * * @summary Get all Visual Mappings for the Visual Style * * @param name Name of the Visual Style * * @return List of all Visual Mappings. * */ @GET @Path("/{name}/mappings") @Produces(MediaType.APPLICATION_JSON) public String getMappings(@PathParam("name") String name) { final VisualStyle style = getStyleByName(name); final Collection<VisualMappingFunction<?, ?>> mappings = style.getAllVisualMappingFunctions(); if(mappings.isEmpty()) { return "[]"; } try { return styleMapper.writeValueAsString(mappings); } catch (JsonProcessingException e) { e.printStackTrace(); throw getError("Could not serialize Mappings.", e, Response.Status.INTERNAL_SERVER_ERROR); } catch(Exception ex) { ex.printStackTrace(); throw getError("Could not serialize Mappings.", ex, Response.Status.INTERNAL_SERVER_ERROR); } } /** * * @summary Get a Visual Mapping associated with the Visual Property * * @param name Name of the Visual Style * @param vp Unique ID of the Visual Property. This should be the unique ID of the VP. * * @return Visual Mapping assigned to the Visual Property * */ @GET @Path("/{name}/mappings/{vp}") @Produces(MediaType.APPLICATION_JSON) public String getMapping(@PathParam("name") String name, @PathParam("vp") String vp) { final VisualStyle style = getStyleByName(name); final VisualMappingFunction<?, ?> mapping = getMappingFunction(vp, style); try { return styleMapper.writeValueAsString(mapping); } catch (JsonProcessingException e) { throw getError("Could not serialize Mapping.", e, Response.Status.INTERNAL_SERVER_ERROR); } } private final VisualMappingFunction<?, ?> getMappingFunction(final String vp, final VisualStyle style) { final VisualLexicon lexicon = getLexicon(); final Set<VisualProperty<?>> allVp = lexicon.getAllVisualProperties(); VisualProperty<?> visualProp = null; for (VisualProperty<?> curVp : allVp) { if (curVp.getIdString().equals(vp)) { visualProp = curVp; break; } } if (visualProp == null) { throw new NotFoundException("Could not find VisualProperty: " + vp); } final VisualMappingFunction<?, ?> mapping = style.getVisualMappingFunction(visualProp); if(mapping == null) { throw new NotFoundException("Could not find visual mapping function for " + vp); } return mapping; } private final String serializeDefaultValues(String name) { final VisualStyle style = getStyleByName(name); final VisualLexicon lexicon = getLexicon(); final Collection<VisualProperty<?>> vps = lexicon.getAllVisualProperties(); try { return styleSerializer.serializeDefaults(vps, style); } catch (IOException e) { throw getError("Could not serialize default values.", e, Response.Status.INTERNAL_SERVER_ERROR); } } private final String serializeDefaultValue(final String styleName, final String vpName) { final VisualStyle style = getStyleByName(styleName); VisualProperty<Object> vp = (VisualProperty<Object>) getVisualProperty(vpName); try { return styleSerializer.serializeDefault(vp, style); } catch (IOException e) { throw getError("Could not serialize default value for " + vpName, e, Response.Status.INTERNAL_SERVER_ERROR); } } private final String serializeRangeValue(final String vpName) { VisualProperty<Object> vp = (VisualProperty<Object>) getVisualProperty(vpName); Range<Object> range = vp.getRange(); if (range.isDiscrete()) { final DiscreteRange<Object> discRange = (DiscreteRange<Object>)range; try { return styleSerializer.serializeDiscreteRange(vp, discRange); } catch (IOException e) { throw getError("Could not serialize default value for " + vpName, e, Response.Status.INTERNAL_SERVER_ERROR); } } else { throw new NotFoundException("Range object is not available for " + vpName); } } private final Set<VisualProperty<?>> getAllVisualProperties() { final VisualLexicon lexicon = getLexicon(); return lexicon.getAllVisualProperties(); } private final VisualProperty<?> getVisualProperty(String vpName) { final VisualLexicon lexicon = getLexicon(); final Collection<VisualProperty<?>> vps = lexicon.getAllVisualProperties(); for (VisualProperty<?> vp : vps) { if (vp.getIdString().equals(vpName)) { return vp; } } return null; } // /////////// Update Default Values /////////////// /** * * @summary Update a default value for the Visual Property * * The body of the request should be a list of key-value pair: * <pre> * [ * { * "visualProperty": VISUAL_PROPERTY_ID, * "value": value * }, ... * ] * </pre> * * @param name Name of the Visual Style * */ @PUT @Path("/{name}/defaults") @Produces(MediaType.APPLICATION_JSON) public Response updateDefaults(@PathParam("name") String name, InputStream is) { final VisualStyle style = getStyleByName(name); final ObjectMapper objMapper = new ObjectMapper(); try { final JsonNode rootNode = objMapper.readValue(is, JsonNode.class); updateVisualProperties(rootNode, style); } catch (Exception e) { throw getError("Could not update default values.", e, Response.Status.INTERNAL_SERVER_ERROR); } return Response.ok().build(); } @SuppressWarnings("unchecked") private final void updateVisualProperties(final JsonNode rootNode, VisualStyle style) { for(JsonNode defaultNode: rootNode) { final String vpName = defaultNode.get(VisualStyleMapper.MAPPING_VP).textValue(); @SuppressWarnings("rawtypes") final VisualProperty vp = getVisualProperty(vpName); if (vp == null) { continue; } final Object value = vp.parseSerializableString(defaultNode.get("value").asText()); if(value != null) { style.setDefaultValue(vp, value); } } } /** * * @summary Get a Visual Style in Cytoscape.js CSS format. * * @param name Name of the Visual Style * * @return Visual Style in Cytoscape.js CSS format. This is always in an array. * */ @GET @Path("/{name}.json") @Produces(MediaType.APPLICATION_JSON) public String getStyle(@PathParam("name") String name) { if(networkViewManager.getNetworkViewSet().isEmpty()) { throw getError("You need at least one view object to use this feature." , new IllegalStateException(), Response.Status.INTERNAL_SERVER_ERROR); } final VisualStyle style = getStyleByName(name); final VizmapWriterFactory jsonVsFact = this.writerListener.getFactory(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); final Set<VisualStyle> styleCollection = new HashSet<VisualStyle>(); styleCollection.add(style); try { final CyWriter styleWriter = jsonVsFact.createWriter(os, styleCollection); styleWriter.run(new HeadlessTaskMonitor()); String jsonString = os.toString("UTF-8"); os.close(); return jsonString; } catch (Exception e) { throw getError("Could not get Visual Style in Cytoscape.js format.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * * This returns JSON version of Visual Style object with full details. Format is simple: * * <pre> * { * "title": (name of this Visual Style), * "defaults": [ default values ], * "mappings": [ Mappings ] * } * </pre> * * Essentially, this is a JSON version of the Visual Style XML file. * * * @summary Get a Visual Style with full details * * @param name Name of the Visual Style * * @return Visual Style in Cytoscape JSON format */ @GET @Path("/{name}") @Produces(MediaType.APPLICATION_JSON) public String getStyleFull(@PathParam("name") String name) { final VisualStyle style = getStyleByName(name); try { return styleSerializer.serializeStyle(getLexicon().getAllVisualProperties(), style); } catch (IOException e) { throw getError("Could not get Visual Style JSON.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * @summary Create a new Visual Style from JSON. * * @return Title of the new Visual Style. */ @POST @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createStyle(InputStream is) { final ObjectMapper objMapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = objMapper.readValue(is, JsonNode.class); VisualStyle style = this.visualStyleMapper.buildVisualStyle(factoryManager, vsFactory, getLexicon(), rootNode); vmm.addVisualStyle(style); // This may be different from the original one if same name exists. final String result = "{\"title\": \""+ style.getTitle() + "\"}"; return Response.status(Response.Status.CREATED).entity(result).build(); } catch (Exception e) { throw getError("Could not create new Visual Style.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * * Create a new Visual Mapping function from JSON and add it to the Style. * * <h3>Discrete Mapping</h3> * <h3>Continuous Mapping</h3> * <h3>Passthrough Mapping</h3> * * @summary Add a new Visual Mapping * * @param name Name of the Visual Style */ @POST @Path("/{name}/mappings") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createMappings(@PathParam("name") String name,InputStream is) { final VisualStyle style = getStyleByName(name); final ObjectMapper objMapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = objMapper.readValue(is, JsonNode.class); this.visualStyleMapper.buildMappings(style, factoryManager, getLexicon(),rootNode); } catch (Exception e) { e.printStackTrace(); throw getError("Could not create new Mapping.", e, Response.Status.INTERNAL_SERVER_ERROR); } return Response.status(Response.Status.CREATED).build(); } /** * * @summary Update name of a Visual Style * * @param name Original name of the Visual Style * */ @PUT @Path("/{name}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void updateStyleName(@PathParam("name") String name, InputStream is) { final VisualStyle style = getStyleByName(name); final ObjectMapper objMapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = objMapper.readValue(is, JsonNode.class); this.visualStyleMapper.updateStyleName(style, getLexicon(), rootNode); } catch (Exception e) { throw getError("Could not update Visual Style title.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * Currently, this is same as POST; it simply replaces existing mapping. * You need to send complete information for the new mappings. * * @summary Update an existing Visual Mapping * * @param name Name of visual Style * @param vp Target Visual Property * */ @PUT @Path("/{name}/mappings/{vp}") @Consumes(MediaType.APPLICATION_JSON) public Response updateMapping(@PathParam("name") String name, @PathParam("vp") String vp, InputStream is) { final VisualStyle style = getStyleByName(name); final VisualMappingFunction<?, ?> currentMapping = getMappingFunction(vp, style); final ObjectMapper objMapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = objMapper.readValue(is, JsonNode.class); this.visualStyleMapper.buildMappings(style, factoryManager, getLexicon(),rootNode); } catch (Exception e) { e.printStackTrace(); throw getError("Could not update Mapping.", e, Response.Status.INTERNAL_SERVER_ERROR); } return Response.ok().build(); } private final VisualStyle getStyleByName(final String name) { final Collection<VisualStyle> styles = vmm.getAllVisualStyles(); for (final VisualStyle style : styles) { if (style.getTitle().equals(name)) { return style; } } throw new NotFoundException("Could not find Visual Style: " + name); } /** * * Check status of Visual Property Dependencies. If a dependency is enables, it has true for "enabled." * * @summary Get all Visual Property Dependency status * * @param name Name of the Visual Style * * @return List of the status of all Visual Property dependencies. * */ @GET @Path("/{name}/dependencies") @Produces(MediaType.APPLICATION_JSON) public String getAllDependencies(@PathParam("name") String name) { final VisualStyle style = getStyleByName(name); final Set<VisualPropertyDependency<?>> dependencies = style.getAllVisualPropertyDependencies(); try { return visualStyleSerializer.serializeDependecies(dependencies); } catch (IOException e) { throw getError("Could not get Visual Property denendencies.", e, Response.Status.INTERNAL_SERVER_ERROR); } } /** * * The body should be the following format: * <pre> * [ * { * "visualPropertyDependnecy" : "DEPENDENCY_ID", * "enabled" : true or false * }, ... {} * ] * </pre> * * @summary Set Visual Property Dependency flags * * @param name Name of Visual Style * */ @PUT @Path("/{name}/dependencies") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void updateDependencies(@PathParam("name") String name, InputStream is) { final VisualStyle style = getStyleByName(name); final ObjectMapper objMapper = new ObjectMapper(); JsonNode rootNode; try { rootNode = objMapper.readValue(is, JsonNode.class); this.visualStyleMapper.updateDependencies(style, rootNode); } catch (Exception e) { throw getError("Could not update Visual Style title.", e, Response.Status.INTERNAL_SERVER_ERROR); } } }
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.hiem._20.unsubscribe.nhin; import java.util.List; import javax.xml.ws.WebServiceContext; import javax.xml.xpath.XPathExpressionException; import org.apache.log4j.Logger; import org.oasis_open.docs.wsn.b_2.Unsubscribe; import org.oasis_open.docs.wsn.b_2.UnsubscribeResponse; import org.oasis_open.docs.wsn.bw_2.UnableToDestroySubscriptionFault; import org.w3c.dom.Element; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType; import gov.hhs.fha.nhinc.cxf.extraction.SAML2AssertionExtractor; import gov.hhs.fha.nhinc.hiem.configuration.ConfigurationManager; import gov.hhs.fha.nhinc.hiem.consumerreference.ReferenceParametersHelper; import gov.hhs.fha.nhinc.hiem.consumerreference.SoapHeaderHelper; import gov.hhs.fha.nhinc.hiem.consumerreference.SoapMessageElements; import gov.hhs.fha.nhinc.hiem.dte.TargetBuilder; import gov.hhs.fha.nhinc.hiem.dte.marshallers.WsntUnsubscribeMarshaller; import gov.hhs.fha.nhinc.hiem.dte.marshallers.WsntUnsubscribeResponseMarshaller; import gov.hhs.fha.nhinc.hiem.processor.faults.ConfigurationException; import gov.hhs.fha.nhinc.hiem.processor.faults.SubscriptionManagerSoapFaultFactory; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import gov.hhs.fha.nhinc.subscription.repository.data.HiemSubscriptionItem; import gov.hhs.fha.nhinc.subscription.repository.service.HiemSubscriptionRepositoryService; import gov.hhs.fha.nhinc.subscription.repository.service.SubscriptionRepositoryException; import gov.hhs.fha.nhinc.unsubscribe.adapter.proxy.HiemUnsubscribeAdapterProxy; import gov.hhs.fha.nhinc.unsubscribe.adapter.proxy.HiemUnsubscribeAdapterProxyObjectFactory; import gov.hhs.fha.nhinc.xmlCommon.XmlUtility; /** * * @author jhoppesc */ public class HiemUnsubscribeImpl { private static final Logger LOG = Logger.getLogger(HiemUnsubscribeImpl.class); public UnsubscribeResponse unsubscribe(Unsubscribe unsubscribeRequest, WebServiceContext context) throws UnableToDestroySubscriptionFault { UnsubscribeResponse response; try { response = unsubscribeOps(unsubscribeRequest, context); } catch (Exception ex) { throw new SubscriptionManagerSoapFaultFactory().getGenericProcessingExceptionFault(ex); } return response; } /** * @param unsubscribeRequest * @param context * @return * @throws UnableToDestroySubscriptionFault * @throws Exception */ private UnsubscribeResponse unsubscribeOps(Unsubscribe unsubscribeRequest, WebServiceContext context) throws UnableToDestroySubscriptionFault, Exception { LOG.debug("Entering HiemUnsubscribeImpl.unsubscribe"); SoapMessageElements soapHeaderElements = new SoapHeaderHelper().getSoapHeaderElements(context); AssertionType assertion = SAML2AssertionExtractor.getInstance().extractSamlAssertion(context); HiemSubscriptionRepositoryService repo = new HiemSubscriptionRepositoryService(); HiemSubscriptionItem subscriptionItem = null; subscriptionItem = populateSubscriptionItem(soapHeaderElements, repo, subscriptionItem); //if has parent, retrieve parent, forward unsubscribe to agency List<HiemSubscriptionItem> childSubscriptions = null; try { childSubscriptions = repo.retrieveByParentSubscriptionReference(subscriptionItem .getSubscriptionReferenceXML()); if (NullChecker.isNotNullish(childSubscriptions)) { LOG.debug("send unsubscribe(s) to child"); for (HiemSubscriptionItem childSubscription : childSubscriptions) { unsubscribeToChild(unsubscribeRequest, childSubscription, assertion); } } else if (isForwardUnsubscribeToAdapter()) { LOG.debug("forward unsubscribe to adapter"); forwardUnsubscribeToAdapter(unsubscribeRequest, soapHeaderElements, assertion); } } catch (SubscriptionRepositoryException ex) { LOG.warn("failed to check for child subscription", ex); } removeFromLocalRepo(repo, subscriptionItem); LOG.debug("Exiting HiemUnsubscribeImpl.unsubscribe"); return new UnsubscribeResponse(); } /** * @param soapHeaderElements * @param repo * @param subscriptionItem * @return * @throws UnableToDestroySubscriptionFault * @throws Exception */ private HiemSubscriptionItem populateSubscriptionItem(SoapMessageElements soapHeaderElements, HiemSubscriptionRepositoryService repo, HiemSubscriptionItem subscriptionItem) throws UnableToDestroySubscriptionFault, Exception { try { subscriptionItem = repo.retrieveByLocalSubscriptionReferenceParameters(soapHeaderElements); } catch (SubscriptionRepositoryException ex) { LOG.error(ex); throw new SubscriptionManagerSoapFaultFactory().getGenericProcessingExceptionFault(ex); } if (subscriptionItem == null) { throw new SubscriptionManagerSoapFaultFactory().getUnableToFindSubscriptionFault(); } return subscriptionItem; } /** * @param repo * @param subscriptionItem * @throws UnableToDestroySubscriptionFault */ private void removeFromLocalRepo(HiemSubscriptionRepositoryService repo, HiemSubscriptionItem subscriptionItem) throws UnableToDestroySubscriptionFault { LOG.debug("invoking subscription storage service to delete subscription"); try { repo.deleteSubscription(subscriptionItem); } catch (SubscriptionRepositoryException ex) { LOG.error("unable to delete subscription. This should result in a unable to remove subscription fault", ex); throw new SubscriptionManagerSoapFaultFactory().getFailedToRemoveSubscriptionFault(ex); } } private boolean isForwardUnsubscribeToAdapter() { boolean forward = false; ConfigurationManager config = new ConfigurationManager(); String mode = ""; try { mode = config.getAdapterSubscriptionMode(); } catch (ConfigurationException ex) { LOG.warn("unable to determine adapter subscription mode"); forward = false; } if (NullChecker.isNotNullish(mode)) { if (!mode.contentEquals(NhincConstants.HIEM_ADAPTER_SUBSCRIPTION_MODE_CREATE_CHILD_DISABLED)) { forward = true; } } return forward; } private void forwardUnsubscribeToAdapter(Unsubscribe parentUnsubscribe, SoapMessageElements parentReferenceParametersElements, AssertionType parentAssertion) throws UnableToDestroySubscriptionFault { LOG.debug("forwarding unsubscribe to adapter"); LOG.debug("target to be filled in by proxy using connection manager"); NhinTargetSystemType target = null; LOG.debug("unmarshalling unsubscribe"); WsntUnsubscribeMarshaller unsubscribeMarshaller = new WsntUnsubscribeMarshaller(); Element unsubscribeElement = unsubscribeMarshaller.marshal(parentUnsubscribe); LOG.debug(XmlUtility.formatElementForLogging(null, unsubscribeElement)); LOG.debug("using reference parameters from parent message [" + parentReferenceParametersElements.getElements().size() + " element(s)]"); LOG.debug("initialize proxy"); HiemUnsubscribeAdapterProxyObjectFactory factory = new HiemUnsubscribeAdapterProxyObjectFactory(); HiemUnsubscribeAdapterProxy proxy = factory.getHiemSubscribeAdapterProxy(); LOG.debug("initialized proxy"); LOG.debug("sending unsubscribe"); Element unsubscribeResponseElement = proxy.unsubscribe(unsubscribeElement, parentReferenceParametersElements, parentAssertion, target); LOG.debug("unsubscribe response received"); LOG.debug("unmarshalling response"); WsntUnsubscribeResponseMarshaller unsubscribeResponseMarshaller = new WsntUnsubscribeResponseMarshaller(); unsubscribeResponseMarshaller.unmarshal(unsubscribeResponseElement); LOG.debug("unmarshalled response"); } private void unsubscribeToChild(Unsubscribe parentUnsubscribe, HiemSubscriptionItem childSubscriptionItem, AssertionType parentAssertion) throws UnableToDestroySubscriptionFault { try { LOG.debug("unsubscribing to child subscription"); LOG.debug("building target"); NhinTargetSystemType target; target = new TargetBuilder().buildSubscriptionManagerTarget(childSubscriptionItem .getSubscriptionReferenceXML()); LOG.debug("target url = " + target.getUrl()); LOG.debug("unmarshalling unsubscribe"); WsntUnsubscribeMarshaller unsubscribeMarshaller = new WsntUnsubscribeMarshaller(); Element unsubscribeElement = unsubscribeMarshaller.marshal(parentUnsubscribe); LOG.debug(XmlUtility.formatElementForLogging(null, unsubscribeElement)); LOG.debug("extracting reference parameters from subscription reference"); ReferenceParametersHelper referenceParametersHelper = new ReferenceParametersHelper(); SoapMessageElements referenceParametersElements = referenceParametersHelper .createReferenceParameterElementsFromSubscriptionReference(childSubscriptionItem .getSubscriptionReferenceXML()); LOG.debug("extracted " + referenceParametersElements.getElements().size() + " element(s)"); LOG.debug("initialize proxy"); HiemUnsubscribeAdapterProxyObjectFactory factory = new HiemUnsubscribeAdapterProxyObjectFactory(); HiemUnsubscribeAdapterProxy proxy = factory.getHiemSubscribeAdapterProxy(); LOG.debug("initialized proxy"); LOG.debug("sending unsubscribe"); Element unsubscribeResponseElement = proxy.unsubscribe(unsubscribeElement, referenceParametersElements, parentAssertion, target); LOG.debug("unsubscribe response received"); LOG.debug("unmarshalling response"); WsntUnsubscribeResponseMarshaller unsubscribeResponseMarshaller = new WsntUnsubscribeResponseMarshaller(); unsubscribeResponseMarshaller.unmarshal(unsubscribeResponseElement); LOG.debug("unmarshalled response"); LOG.debug("invoking subscription repository to remove child subscription"); HiemSubscriptionRepositoryService repo = new HiemSubscriptionRepositoryService(); repo.deleteSubscription(childSubscriptionItem); LOG.debug("child subscription deleted"); } catch (SubscriptionRepositoryException ex) { LOG.error("failed to remove child subscription for repository"); throw new SubscriptionManagerSoapFaultFactory().getFailedToRemoveSubscriptionFault(ex); } catch (XPathExpressionException ex) { LOG.error("failed to parse subscription reference"); throw new SubscriptionManagerSoapFaultFactory().getFailedToRemoveSubscriptionFault(ex); } } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.security.authentication; import static org.junit.Assert.assertTrue; import alluxio.Configuration; import alluxio.ConfigurationTestUtils; import alluxio.PropertyKey; import alluxio.exception.status.UnauthenticatedException; import alluxio.network.thrift.ThriftUtils; import alluxio.util.network.NetworkAddressUtils; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.transport.TTransportFactory; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.net.InetSocketAddress; import javax.security.sasl.AuthenticationException; /** * Unit test for methods of {@link TransportProvider}. * * In order to test methods that return kinds of TTransport for connection in different mode, we * build Thrift servers and clients with specific TTransport, and let them connect. */ public final class TransportProviderTest { private TThreadPoolServer mServer; private InetSocketAddress mServerAddress; private TTransport mBaseTransport; private TServerSocket mServerTSocket; private TransportProvider mTransportProvider; /** * The exception expected to be thrown. */ @Rule public ExpectedException mThrown = ExpectedException.none(); /** * Sets up the server before running a test. */ @Before public void before() throws Exception { // Use port 0 to assign each test case an available port (possibly different) String localhost = NetworkAddressUtils.getLocalHostName(); mServerTSocket = new TServerSocket(new InetSocketAddress(localhost, 0)); int port = ThriftUtils.getThriftPort(mServerTSocket); mServerAddress = new InetSocketAddress(localhost, port); mBaseTransport = ThriftUtils.createThriftSocket(mServerAddress); } @After public void after() { ConfigurationTestUtils.resetConfiguration(); } /** * In NOSASL mode, the TTransport used should be the same as Alluxio original code. */ @Test public void nosaslAuthentrication() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.NOSASL.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // create client and connect to server TTransport client = mTransportProvider.getClientTransport(mServerAddress); client.open(); assertTrue(client.isOpen()); // clean up client.close(); mServer.stop(); } /** * In SIMPLE mode, the TTransport mechanism is PLAIN. When server authenticate the connected * client user, it use {@link SimpleAuthenticationProvider}. */ @Test public void simpleAuthentication() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // when connecting, authentication happens. It is a no-op in Simple mode. TTransport client = mTransportProvider.getClientTransport(mServerAddress); client.open(); assertTrue(client.isOpen()); // clean up client.close(); mServer.stop(); } /** * In SIMPLE mode, if client's username is null, an exception should be thrown in client side. */ @Test public void simpleAuthenticationNullUser() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // check case that user is null mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage("PLAIN: authorization ID and password must be specified"); ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport(null, "whatever", null, mServerAddress); } /** * In SIMPLE mode, if client's password is null, an exception should be thrown in client side. */ @Test public void simpleAuthenticationNullPassword() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // check case that password is null mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage("PLAIN: authorization ID and password must be specified"); ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport("anyone", null, null, mServerAddress); } /** * In SIMPLE mode, if client's username is empty, an exception should be thrown in server side. */ @Test public void simpleAuthenticationEmptyUser() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // check case that user is empty mThrown.expect(TTransportException.class); mThrown.expectMessage("Peer indicated failure: Plain authentication failed: No authentication" + " identity provided"); TTransport client = ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport("", "whatever", null, mServerAddress); try { client.open(); } finally { mServer.stop(); } } /** * In SIMPLE mode, if client's password is empty, an exception should be thrown in server side. * Although password is actually not used and we do not really authenticate the user in SIMPLE * mode, we need the Plain SASL server has ability to check empty password. */ @Test public void simpleAuthenticationEmptyPassword() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // check case that password is empty mThrown.expect(TTransportException.class); mThrown.expectMessage( "Peer indicated failure: Plain authentication failed: No password " + "provided"); TTransport client = ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport("anyone", "", null, mServerAddress); try { client.open(); } finally { mServer.stop(); } } /** * In CUSTOM mode, the TTransport mechanism is PLAIN. When server authenticate the connected * client user, it use configured AuthenticationProvider. If the username:password pair matches, a * connection should be built. */ @Test public void customAuthenticationExactNamePasswordMatch() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM.getAuthName()); Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_CUSTOM_PROVIDER_CLASS, ExactlyMatchAuthenticationProvider.class.getName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // when connecting, authentication happens. User's name:pwd pair matches and auth pass. TTransport client = ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport(ExactlyMatchAuthenticationProvider.USERNAME, ExactlyMatchAuthenticationProvider.PASSWORD, null, mServerAddress); client.open(); assertTrue(client.isOpen()); // clean up client.close(); mServer.stop(); } /** * In CUSTOM mode, If the username:password pair does not match based on the configured * AuthenticationProvider, an exception should be thrown in server side. */ @Test public void customAuthenticationExactNamePasswordNotMatch() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM.getAuthName()); Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_CUSTOM_PROVIDER_CLASS, ExactlyMatchAuthenticationProvider.class.getName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // User with wrong password can not pass auth, and throw exception. TTransport wrongClient = ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport(ExactlyMatchAuthenticationProvider.USERNAME, "wrong-password", null, mServerAddress); mThrown.expect(TTransportException.class); mThrown.expectMessage( "Peer indicated failure: Plain authentication failed: " + "User authentication fails"); try { wrongClient.open(); } finally { mServer.stop(); } } /** * In CUSTOM mode, if client's username is null, an exception should be thrown in client side. */ @Test public void customAuthenticationNullUser() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // check case that user is null mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage("PLAIN: authorization ID and password must be specified"); ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport(null, ExactlyMatchAuthenticationProvider.PASSWORD, null, mServerAddress); } /** * In CUSTOM mode, if client's password is null, an exception should be thrown in client side. */ @Test public void customAuthenticationNullPassword() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM.getAuthName()); mTransportProvider = TransportProvider.Factory.create(); // check case that password is null mThrown.expect(UnauthenticatedException.class); mThrown.expectMessage("PLAIN: authorization ID and password must be specified"); ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport(ExactlyMatchAuthenticationProvider.USERNAME, null, null, mServerAddress); } /** * In CUSTOM mode, if client's username is empty, an exception should be thrown in server side. */ @Test public void customAuthenticationEmptyUser() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM.getAuthName()); Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_CUSTOM_PROVIDER_CLASS, ExactlyMatchAuthenticationProvider.class.getName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // check case that user is empty mThrown.expect(TTransportException.class); mThrown.expectMessage("Peer indicated failure: Plain authentication failed: No authentication" + " identity provided"); TTransport client = ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport("", ExactlyMatchAuthenticationProvider.PASSWORD, null, mServerAddress); try { client.open(); } finally { mServer.stop(); } } /** * In CUSTOM mode, if client's password is empty, an exception should be thrown in server side. */ @Test public void customAuthenticationEmptyPassword() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM.getAuthName()); Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_CUSTOM_PROVIDER_CLASS, ExactlyMatchAuthenticationProvider.class.getName()); mTransportProvider = TransportProvider.Factory.create(); // start server startServerThread(); // check case that password is empty mThrown.expect(TTransportException.class); mThrown.expectMessage( "Peer indicated failure: Plain authentication failed: No password provided"); TTransport client = ((PlainSaslTransportProvider) mTransportProvider) .getClientTransport(ExactlyMatchAuthenticationProvider.USERNAME, "", null, mServerAddress); try { client.open(); } finally { mServer.stop(); } } /** * TODO(dong): In KERBEROS mode, ... * Tests that an exception is thrown when trying to use KERBEROS mode. */ @Test public void kerberosAuthentication() throws Exception { Configuration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.KERBEROS.getAuthName()); // throw unsupported exception currently mThrown.expect(UnsupportedOperationException.class); mThrown.expectMessage("Kerberos is not supported currently."); mTransportProvider = TransportProvider.Factory.create(); } private void startServerThread() throws Exception { // create args and use them to build a Thrift TServer TTransportFactory tTransportFactory = mTransportProvider.getServerTransportFactory("test"); mServer = new TThreadPoolServer( new TThreadPoolServer.Args(mServerTSocket).maxWorkerThreads(2).minWorkerThreads(1) .processor(null).transportFactory(tTransportFactory) .protocolFactory(new TBinaryProtocol.Factory(true, true))); // start the server in a new thread Thread serverThread = new Thread(new Runnable() { @Override public void run() { mServer.serve(); } }); serverThread.start(); // ensure server is running, and break if it does not start serving in 2 seconds. int count = 40; while (!mServer.isServing() && serverThread.isAlive()) { if (count <= 0) { throw new RuntimeException("TThreadPoolServer does not start serving"); } Thread.sleep(50); count--; } } /** * This customized authentication provider is used in CUSTOM mode. It authenticates the user by * verifying the specific username:password pair. */ public static class ExactlyMatchAuthenticationProvider implements AuthenticationProvider { static final String USERNAME = "alluxio"; static final String PASSWORD = "correct-password"; @Override public void authenticate(String user, String password) throws AuthenticationException { if (!user.equals(USERNAME) || !password.equals(PASSWORD)) { throw new AuthenticationException("User authentication fails"); } } } }
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.wizard; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.JBColor; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Wizard header component */ public class WizardStepHeaderPanel extends JPanel { @NotNull String myTitle = "Title Label"; @Nullable String myDescription; @Nullable Icon myWizardIcon; @Nullable Icon myStepIcon; @Nullable private JLabel myTitleLabel; @NotNull private ComponentHolder<String, JLabel> myDescriptionLabel = new LabelHolder(); @NotNull private ComponentHolder<Icon, ImageComponent> myWizardIconComponent = new ImageComponentHolder(); @NotNull private ComponentHolder<Icon, ImageComponent> myStepIconComponent = new ImageComponentHolder(); public WizardStepHeaderPanel() { setBorder(new EmptyBorder(WizardConstants.STUDIO_WIZARD_INSETS)); //noinspection UseJBColor setForeground(Color.WHITE); setBackground(WizardConstants.ANDROID_NPW_HEADER_COLOR); updateHeader(); } private static GridConstraints createHeaderLabelGridConstraints(int row, int column, int anchor) { return new GridConstraints(row, column, 1, 1, anchor, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null); } public static WizardStepHeaderPanel create(@NotNull final JBColor headerColor, @Nullable Icon wizardIcon, @Nullable Icon stepIcon, @NotNull String title, @Nullable String description) { final WizardStepHeaderPanel panel = new WizardStepHeaderPanel(); panel.setBackground(headerColor); panel.setTitle(title); panel.setDescription(description); panel.setStepIcon(stepIcon); panel.setWizardIcon(wizardIcon); UIManager.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { // Force an update of static JBColor.DARK. This is required to show the correct color after a LookAndFeel change. JBColor.setDark(UIUtil.isUnderDarcula()); panel.setBackground(headerColor); // The font size was not set correctly after a LookAndFeel change from Darcula to Standard. Font font = UIManager.getFont("Label.font"); panel.myTitleLabel.setFont(new Font(font.getFontName(), font.getStyle(), 24)); } }); return panel; } public void setTitle(@Nullable String title) { myTitle = StringUtil.notNullize(title, "Title Label"); updateHeader(); } public void setDescription(@Nullable String description) { myDescription = description; updateHeader(); } public void setStepIcon(@Nullable Icon stepIcon) { myStepIcon = stepIcon; updateHeader(); } public void setWizardIcon(@Nullable Icon wizardIcon) { myWizardIcon = wizardIcon; updateHeader(); } private void updateHeader() { boolean updateLayout = false; if (myTitleLabel == null) { myTitleLabel = new JLabel(myTitle); updateLayout = true; } myTitleLabel.setText(myTitle); updateLayout |= myDescriptionLabel.updateValue(StringUtil.nullize(myDescription, true)) || myWizardIconComponent.updateValue(myWizardIcon) || myStepIconComponent.updateValue(myStepIcon); if (updateLayout) { final int rows = myDescriptionLabel.getComponent() == null ? 1 : 2; final int columns = 1 + (myWizardIconComponent.getComponent() == null ? 0 : 1) + (myStepIconComponent.getComponent() == null ? 0 : 1); for (Component component : getComponents()) { remove(component); } setLayout(new GridLayoutManager(rows, columns, new Insets(18, 0, 12, 0), 2, 2)); int currentColumn = addIconIfExists(myWizardIconComponent.getComponent(), 0, rows) ? 1 : 0; addLabels(myTitleLabel, myDescriptionLabel.getComponent(), currentColumn); addIconIfExists(myStepIconComponent.getComponent(), currentColumn + 1, rows); } } private void addLabels(@NotNull JLabel titleLabel, @Nullable JLabel descriptionLabel, int column) { boolean hasDescription = descriptionLabel != null; int anchor = hasDescription ? GridConstraints.ANCHOR_SOUTHWEST : GridConstraints.ANCHOR_WEST; titleLabel.setForeground(getForeground()); titleLabel.setFont(titleLabel.getFont().deriveFont(24f)); add(titleLabel, createHeaderLabelGridConstraints(0, column, anchor)); if (hasDescription) { descriptionLabel.setForeground(getForeground()); add(descriptionLabel, createHeaderLabelGridConstraints(1, column, GridConstraints.ANCHOR_NORTHWEST)); } } private boolean addIconIfExists(@Nullable ImageComponent iconComponent, int column, int spanningRows) { if (iconComponent != null) { GridConstraints imageConstraints = new GridConstraints(0, column, spanningRows, 1, GridConstraints.ANCHOR_NORTHWEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(60, 60), null); add(iconComponent, imageConstraints); return true; } else { return false; } } private static abstract class ComponentHolder<V, C extends JComponent> { @Nullable private C myComponent; public final boolean updateValue(@Nullable V value) { boolean updateLayout; if (value == null) { updateLayout = myComponent != null; myComponent = null; } else { if (myComponent == null) { updateLayout = true; myComponent = createComponent(); } else { updateLayout = false; } setValue(myComponent, value); } return updateLayout; } protected abstract void setValue(@NotNull C component, @NotNull V value); @NotNull protected abstract C createComponent(); @Nullable public final C getComponent() { return myComponent; } } private static class ImageComponentHolder extends ComponentHolder<Icon, ImageComponent> { @Override protected void setValue(@NotNull ImageComponent component, @NotNull Icon value) { component.setIcon(value); } @NotNull @Override protected ImageComponent createComponent() { return new ImageComponent(); } } private static class LabelHolder extends ComponentHolder<String, JLabel> { @Override protected void setValue(@NotNull JLabel component, @NotNull String value) { component.setText(value); } @NotNull @Override protected JLabel createComponent() { return new JLabel(); } } }
package com.smidur.aventon; import android.*; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.PersistableBundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.FragmentManager; import com.amazonaws.mobile.AWSMobileClient; import com.amazonaws.mobile.user.IdentityManager; import com.smidur.aventon.cloud.ApiGatewayController; import com.smidur.aventon.managers.RideManager; import com.smidur.aventon.model.SyncRideSummary; import com.smidur.aventon.navigation.NavigationDrawer; import com.smidur.aventon.utilities.GpsUtil; import com.smidur.aventon.utilities.NotificationUtil; import java.util.concurrent.CountDownLatch; /** This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * Copyright 2020, Gerardo Marquez. */ public class MainActivity extends AppCompatActivity implements View.OnClickListener { /** Class name for log messages. */ private static final String LOG_TAG = MainActivity.class.getSimpleName(); /** Bundle key for saving/restoring the toolbar title. */ private static final String BUNDLE_KEY_TOOLBAR_TITLE = "title"; /** The identity manager used to keep track of the current user account. */ private IdentityManager identityManager; /** The toolbar view control. */ private Toolbar toolbar; /** Our navigation drawer class for handling navigation drawer logic. */ private NavigationDrawer navigationDrawer; /** The helper class used to toggle the left navigation drawer open and closed. */ private ActionBarDrawerToggle drawerToggle; /** Data to be passed between fragments. */ private Bundle fragmentBundle; private Button signOutButton; /** * Initializes the Toolbar for use with the activity. */ private void setupToolbar(final Bundle savedInstanceState) { toolbar = (Toolbar) findViewById(R.id.toolbar); // Set up the activity to use this toolbar. As a side effect this sets the Toolbar's title // to the activity's title. setSupportActionBar(toolbar); if (savedInstanceState != null) { // Some IDEs such as Android Studio complain about possible NPE without this check. assert getSupportActionBar() != null; // Restore the Toolbar's title. getSupportActionBar().setTitle( savedInstanceState.getCharSequence(BUNDLE_KEY_TOOLBAR_TITLE)); } } /** * Initializes the sign-in and sign-out buttons. */ private void setupSignInButtons() { signOutButton = (Button) findViewById(R.id.button_signout); signOutButton.setOnClickListener(this); } /** * Initializes the navigation drawer menu to allow toggling via the toolbar or swipe from the * side of the screen. */ private void setupNavigationMenu(final Bundle savedInstanceState) { final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); final ListView drawerItems = (ListView) findViewById(R.id.nav_drawer_items); // Create the navigation drawer. navigationDrawer = new NavigationDrawer(this, toolbar, drawerLayout, drawerItems, R.id.main_fragment_container); String mode = getIntent().getStringExtra("mode"); if(mode != null && mode.equals("passenger")) { navigationDrawer.addDemoFeatureToMenu(NavigationDrawer.Screen.PASSENGER_SCHEDULE_FRAGMENT); } else if (mode != null && mode.equals("driver")) { navigationDrawer.addDemoFeatureToMenu(NavigationDrawer.Screen.DRIVER_LOOK_FOR_RIDE); } if (savedInstanceState == null) { // Add the home fragment to be displayed initially. navigationDrawer.showHome(MainActivity.this,getIntent()); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if(intent.hasExtra("confirm_ride")) { this.getIntent().putExtra("confirm_ride",true); } if(intent.hasExtra("reject_ride")) { NotificationUtil.i(this).cancelIncomingRideRequestNotification(); } } @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); onContinueOnCreate(savedInstanceState); } private void onContinueOnCreate(final Bundle savedInstanceState) { // Obtain a reference to the mobile client. It is created in the Application class, // but in case a custom Application class is not used, we initialize it here if necessary. AWSMobileClient.initializeMobileClientIfNecessary(this); // Obtain a reference to the mobile client. It is created in the Application class. final AWSMobileClient awsMobileClient = AWSMobileClient.defaultMobileClient(); // Obtain a reference to the identity manager. identityManager = awsMobileClient.getIdentityManager(); setContentView(R.layout.activity_main); setupToolbar(savedInstanceState); setupNavigationMenu(savedInstanceState); setupSignInButtons(); } @Override protected void onResume() { super.onResume(); if (!AWSMobileClient.defaultMobileClient().getIdentityManager().isUserSignedIn()) { // In the case that the activity is restarted by the OS after the application // is killed we must redirect to the splash activity to handle the sign-in flow. Intent intent = new Intent(MainActivity.this, SplashActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return; } } @Override public boolean onOptionsItemSelected(final MenuItem item) { // Handle action bar item clicks here excluding the home button. return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(final Bundle bundle) { super.onSaveInstanceState(bundle); // Save the title so it will be restored properly to match the view loaded when rotation // was changed or in case the activity was destroyed. if (toolbar != null) { bundle.putCharSequence(BUNDLE_KEY_TOOLBAR_TITLE, toolbar.getTitle()); } } @Override public void onClick(final View view) { if (view == signOutButton) { // The user is currently signed in with a provider. Sign out of that provider. identityManager.signOut(); startActivity(new Intent(this, SignInActivity.class)); finish(); return; } // ... add any other button handling code here ... } @Override protected void onPause() { super.onPause(); } @Override public void onBackPressed() { final FragmentManager fragmentManager = this.getSupportFragmentManager(); if (navigationDrawer.isDrawerOpen()) { navigationDrawer.closeDrawer(); return; } moveTaskToBack(false); // if (fragmentManager.getBackStackEntryCount() == 0) { // if (fragmentManager.findFragmentByTag(HomeDemoFragment.class.getSimpleName()) == null) { // final Class fragmentClass = HomeDemoFragment.class; // // if we aren't on the home fragment, navigate home. // final Fragment fragment = Fragment.instantiate(this, fragmentClass.getName()); // // fragmentManager // .beginTransaction() // .replace(R.id.main_fragment_container, fragment, fragmentClass.getSimpleName()) // .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) // .commit(); // // // Set the title for the fragment. // final ActionBar actionBar = this.getSupportActionBar(); // if (actionBar != null) { // actionBar.setTitle(getString(R.string.app_name)); // } // return; // } // } } /** * Stores data to be passed between fragments. * @param fragmentBundle fragment data */ public void setFragmentBundle(final Bundle fragmentBundle) { this.fragmentBundle = fragmentBundle; } /** * Gets data to be passed between fragments. * @return fragmentBundle fragment data */ public Bundle getFragmentBundle() { return this.fragmentBundle; } }
/* * Copyright 2017 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.realm; import android.os.Handler; import android.os.HandlerThread; import android.os.SystemClock; import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import io.realm.internal.OsRealmConfig; import io.realm.log.RealmLog; import io.realm.objectserver.utils.Constants; import io.realm.objectserver.utils.UserFactory; import io.realm.permissions.AccessLevel; import io.realm.permissions.Permission; import io.realm.permissions.PermissionOffer; import io.realm.permissions.PermissionRequest; import io.realm.permissions.UserCondition; import io.realm.rule.RunTestInLooperThread; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(AndroidJUnit4.class) public class PermissionManagerTests extends StandardIntegrationTest { private SyncUser user; @Before public void setUpTest() { user = UserFactory.createUniqueUser(); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_noLongerValidWhenPermissionManagerIsClosed() { final PermissionManager pm = user.getPermissionManager(); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isValid()); pm.close(); assertFalse(permissions.isValid()); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { pm.close(); fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_updatedWithNewRealms() { final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); // Create new Realm, which should create a new Permission entry SyncConfiguration config2 = new SyncConfiguration.Builder(user, Constants.USER_REALM_2) .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { fail(error.toString()); } }) .build(); final Realm secondRealm = Realm.getInstance(config2); looperThread.closeAfterTest(secondRealm); // Wait for the permission Result to report the new Realms looperThread.keepStrongReference(permissions); permissions.addChangeListener(new RealmChangeListener<RealmResults<Permission>>() { @Override public void onChange(RealmResults<Permission> permissions) { RealmLog.error(String.format("2ndCallback: Size: %s, Permissions: %s", permissions.size(), Arrays.toString(permissions.toArray()))); Permission p = permissions.where().endsWith("path", "tests2").findFirst(); if (p != null) { assertTrue(p.mayRead()); assertTrue(p.mayWrite()); assertTrue(p.mayManage()); looperThread.testComplete(); } } }); } @Override public void onError(ObjectServerError error) { fail("Could not open Realm: " + error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_updatedWithNewRealms_stressTest() { final int TEST_SIZE = 10; final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); for (int i = 0; i < TEST_SIZE; i++) { SyncConfiguration configNew = new SyncConfiguration.Builder(user, "realm://" + Constants.HOST + "/~/test" + i).build(); Realm newRealm = Realm.getInstance(configNew); looperThread.closeAfterTest(newRealm); } // Wait for the permission Result to report the new Realms looperThread.keepStrongReference(permissions); permissions.addChangeListener(new RealmChangeListener<RealmResults<Permission>>() { @Override public void onChange(RealmResults<Permission> permissions) { RealmLog.error(String.format("Size: %s, Permissions: %s", permissions.size(), Arrays.toString(permissions.toArray()))); Permission p = permissions.where().endsWith("path", "test" + (TEST_SIZE - 1)).findFirst(); if (p != null) { assertTrue(p.mayRead()); assertTrue(p.mayWrite()); assertTrue(p.mayManage()); looperThread.testComplete(); } } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_closed() throws IOException { PermissionManager pm = user.getPermissionManager(); pm.close(); thrown.expect(IllegalStateException.class); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail(); } @Override public void onError(ObjectServerError error) { fail(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_clientReset() { final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { // Simulate reset after first request succeeded to make sure that session is // alive. SyncManager.simulateClientReset(SyncManager.getSession(pm.permissionRealmConfig)); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.CLIENT_RESET, error.getErrorCode()); looperThread.testComplete(); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getPermissions_addTaskAfterClientReset() { final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { // Simulate reset after first request succeeded to make sure that session is // alive. SyncManager.simulateClientReset(SyncManager.getSession(pm.permissionRealmConfig)); // 1. Run task that fail pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.CLIENT_RESET, error.getErrorCode()); // 2. Then try to add another pm.getDefaultPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.CLIENT_RESET, error.getErrorCode()); looperThread.testComplete(); } }); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Ignore("The PermissionManager can only be opened from the main thread") @Test public void clientResetOnMultipleThreads() { HandlerThread thread1 = new HandlerThread("handler1"); thread1.start(); Handler handler1 = new Handler(thread1.getLooper()); HandlerThread thread2 = new HandlerThread("handler2"); thread2.start(); Handler handler2 = new Handler(thread1.getLooper()); final AtomicReference<PermissionManager> pm1 = new AtomicReference<>(null); final AtomicReference<PermissionManager> pm2 = new AtomicReference<>(null); final CountDownLatch pmsOpened = new CountDownLatch(1); // 1) Thread 1: Open PermissionManager and check permissions handler1.post(new Runnable() { @Override public void run() { PermissionManager pm = user.getPermissionManager(); pm1.set(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertInitialPermissions(permissions); pmsOpened.countDown(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } }); // 2) Thread 2: Open PermissionManager and check permissions handler2.post(new Runnable() { @Override public void run() { PermissionManager pm = user.getPermissionManager(); pm2.set(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertInitialPermissions(permissions); pmsOpened.countDown(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } }); TestHelper.awaitOrFail(pmsOpened); // 3) Trigger Client Reset SyncManager.simulateClientReset(SyncManager.getSession(pm1.get().permissionRealmConfig)); SyncManager.simulateClientReset(SyncManager.getSession(pm2.get().permissionRealmConfig)); // 4) Thread 1: Attempt to get permissions should trigger a Client Reset final CountDownLatch clientResetThread1 = new CountDownLatch(1); final CountDownLatch clientResetThread2 = new CountDownLatch(1); handler1.post(new Runnable() { @Override public void run() { final PermissionManager pm = pm1.get(); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail("Client reset should have been triggered"); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.CLIENT_RESET, error.getErrorCode()); pm.close(); assertFalse(new File(pm.permissionRealmConfig.getPath()).exists()); clientResetThread1.countDown(); } }); } }); // 5) Thread 2: Attempting to get permissions should also trigger a Client Reset even though // Thread 1 just executed it TestHelper.awaitOrFail(clientResetThread1); handler2.post(new Runnable() { @Override public void run() { final PermissionManager pm = pm2.get(); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail("Client reset should have been triggered"); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.CLIENT_RESET, error.getErrorCode()); pm.close(); clientResetThread2.countDown(); } }); } }); TestHelper.awaitOrFail(clientResetThread2); // 6) After closing the PermissionManager, re-opening it again should work fine final CountDownLatch newPmOpenedAndReady = new CountDownLatch(1); handler1.post(new Runnable() { @Override public void run() { final PermissionManager pm = user.getPermissionManager(); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertInitialPermissions(permissions); pm.close(); newPmOpenedAndReady.countDown(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } }); TestHelper.awaitOrFail(newPmOpenedAndReady); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getDefaultPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getDefaultPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialDefaultPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getDefaultPermissions_noLongerValidWhenPermissionManagerIsClosed() { final PermissionManager pm = user.getPermissionManager(); pm.getDefaultPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { try { assertTrue(permissions.isValid()); } finally { pm.close(); } assertFalse(permissions.isValid()); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { pm.close(); fail(error.toString()); } }); } @Test @Ignore("FIXME Add once `setPermissions` are implemented") @RunTestInLooperThread(emulateMainThread = true) public void getDefaultPermissions_updatedWithNewRealms() { } @Test @RunTestInLooperThread(emulateMainThread = true) public void getDefaultPermissions_closed() throws IOException { PermissionManager pm = user.getPermissionManager(); pm.close(); thrown.expect(IllegalStateException.class); pm.getDefaultPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { fail(); } @Override public void onError(ObjectServerError error) { fail(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void permissionManagerAsyncTask_handlePermissionRealmError() throws NoSuchFieldException, IllegalAccessException { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); // Simulate error in the permission Realm Field permissionConfigField = pm.getClass().getDeclaredField("permissionRealmError"); permissionConfigField.setAccessible(true); final ObjectServerError error = new ObjectServerError(ErrorCode.UNKNOWN, "Boom"); permissionConfigField.set(pm, error); PermissionManager.ApplyPermissionsCallback callback = new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { fail(); } @Override public void onError(ObjectServerError error) { assertTrue(error.getErrorMessage().startsWith("Error occurred in Realm")); assertTrue(error.getErrorMessage().contains("Permission Realm")); assertEquals(ErrorCode.UNKNOWN, error.getErrorCode()); looperThread.testComplete(); } }; // Create dummy task that can trigger the error reporting runTask(pm, callback); } @Test @RunTestInLooperThread(emulateMainThread = true) public void permissionManagerAsyncTask_handleManagementRealmError() throws NoSuchFieldException, IllegalAccessException { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); // Simulate error in the permission Realm final ObjectServerError error = new ObjectServerError(ErrorCode.UNKNOWN, "Boom"); setRealmError(pm, "managementRealmError", error); PermissionManager.ApplyPermissionsCallback callback = new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { fail(); } @Override public void onError(ObjectServerError error) { assertTrue(error.getErrorMessage().startsWith("Error occurred in Realm")); assertTrue(error.getErrorMessage().contains("Management Realm")); assertEquals(ErrorCode.UNKNOWN, error.getErrorCode()); looperThread.testComplete(); } }; // Create dummy task that can trigger the error reporting runTask(pm, callback); } @Test @RunTestInLooperThread(emulateMainThread = true) public void permissionManagerAsyncTask_handleTwoErrorsSameErrorCode() throws NoSuchFieldException, IllegalAccessException { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); // Simulate error in the permission Realm setRealmError(pm, "managementRealmError", new ObjectServerError(ErrorCode.CONNECTION_CLOSED, "Boom1")); // Simulate error in the management Realm setRealmError(pm, "permissionRealmError", new ObjectServerError(ErrorCode.CONNECTION_CLOSED, "Boom2")); PermissionManager.ApplyPermissionsCallback callback = new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.CONNECTION_CLOSED, error.getErrorCode()); assertTrue(error.toString().contains("Boom1")); assertTrue(error.toString().contains("Boom2")); looperThread.testComplete(); } }; // Create dummy task that can trigger the error reporting runTask(pm, callback); } @Test @RunTestInLooperThread(emulateMainThread = true) public void permissionManagerAsyncTask_handleTwoErrorsDifferentErrorCode() throws NoSuchFieldException, IllegalAccessException { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); // Simulate error in the permission Realm setRealmError(pm, "managementRealmError", new ObjectServerError(ErrorCode.CONNECTION_CLOSED, "Boom1")); // Simulate error in the management Realm setRealmError(pm, "permissionRealmError", new ObjectServerError(ErrorCode.SESSION_CLOSED, "Boom2")); PermissionManager.ApplyPermissionsCallback callback = new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.UNKNOWN, error.getErrorCode()); assertTrue(error.toString().contains(ErrorCode.CONNECTION_CLOSED.toString())); assertTrue(error.toString().contains(ErrorCode.SESSION_CLOSED.toString())); looperThread.testComplete(); } }; // Create dummy task that can trigger the error reporting runTask(pm, callback); } @Test @RunTestInLooperThread(emulateMainThread = true) public void applyPermissions_nonAdminUserFails() { SyncUser user2 = UserFactory.createUniqueUser(); String otherUsersUrl = createRemoteRealm(user2, "test"); PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); // Create request for setting permissions on another users Realm, // i.e. user making the request do not have manage rights. UserCondition condition = UserCondition.userId(user.getIdentity()); AccessLevel accessLevel = AccessLevel.WRITE; PermissionRequest request = new PermissionRequest(condition, otherUsersUrl, accessLevel); pm.applyPermissions(request, new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.ACCESS_DENIED, error.getErrorCode()); looperThread.testComplete(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void applyPermissions_wrongUrlFails() { String wrongUrl = createRemoteRealm(user, "test") + "-notexisting"; PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); // Create request for setting permissions on another users Realm, // i.e. user making the request do not have manage rights. UserCondition condition = UserCondition.userId(user.getIdentity()); AccessLevel accessLevel = AccessLevel.WRITE; PermissionRequest request = new PermissionRequest(condition, wrongUrl, accessLevel); pm.applyPermissions(request, new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { fail(); } @Override public void onError(ObjectServerError error) { // FIXME: Should be 614, see https://github.com/realm/ros/issues/429 assertEquals(ErrorCode.INVALID_PARAMETERS, error.getErrorCode()); looperThread.testComplete(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void applyPermissions_withUserId() { final SyncUser user2 = UserFactory.createUniqueUser(); String url = createRemoteRealm(user2, "test"); PermissionManager pm2 = user2.getPermissionManager(); looperThread.closeAfterTest(pm2); // Create request for giving `user` WRITE permissions to `user2`'s Realm. UserCondition condition = UserCondition.userId(user.getIdentity()); AccessLevel accessLevel = AccessLevel.WRITE; PermissionRequest request = new PermissionRequest(condition, url, accessLevel); pm2.applyPermissions(request, new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertPermissionPresent(permissions, user, "/test", AccessLevel.WRITE); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void applyPermissions_withUsername() { String user1Username = TestHelper.getRandomEmail(); String user2Username = TestHelper.getRandomEmail(); final SyncUser user1 = UserFactory.createUser(user1Username); final SyncUser user2 = UserFactory.createUser(user2Username); PermissionManager pm1 = user1.getPermissionManager(); looperThread.closeAfterTest(pm1); // Create request for giving `user2` WRITE permissions to `user1`'s Realm. UserCondition condition = UserCondition.username(user2Username); AccessLevel accessLevel = AccessLevel.WRITE; String url = createRemoteRealm(user1, "test"); PermissionRequest request = new PermissionRequest(condition, url, accessLevel); pm1.applyPermissions(request, new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { PermissionManager pm2 = user2.getPermissionManager(); looperThread.closeAfterTest(pm2); pm2.getPermissions(new PermissionManager.PermissionsCallback() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertPermissionPresent(permissions, user2, user1.getIdentity() + "/test", AccessLevel.WRITE); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void applyPermissions_usersWithNoExistingPermissions() { final SyncUser user1 = UserFactory.createUser("user1@realm.io"); final SyncUser user2 = UserFactory.createUser("user2@realm.io"); PermissionManager pm1 = user1.getPermissionManager(); looperThread.closeAfterTest(pm1); // Create request for giving all users with no existing permissions WRITE permissions to `user1`'s Realm. UserCondition condition = UserCondition.noExistingPermissions(); AccessLevel accessLevel = AccessLevel.WRITE; final String url = createRemoteRealm(user1, "test"); PermissionRequest request = new PermissionRequest(condition, url, accessLevel); pm1.applyPermissions(request, new PermissionManager.ApplyPermissionsCallback() { @Override public void onSuccess() { // Default permissions are not recorded in the __permission Realm for user2 // Only way to check is by opening the Realm. SyncConfiguration config = new SyncConfiguration.Builder(user2, url) .waitForInitialRemoteData() .errorHandler(new SyncSession.ErrorHandler() { @Override public void onError(SyncSession session, ObjectServerError error) { fail(error.toString()); } }) .build(); RealmAsyncTask task = Realm.getInstanceAsync(config, new Realm.Callback() { @Override public void onSuccess(Realm realm) { realm.close(); looperThread.testComplete(); } @Override public void onError(Throwable exception) { fail(exception.toString()); } }); looperThread.keepStrongReference(task); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void makeOffer() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); String url = createRemoteRealm(user, "test"); PermissionOffer offer = new PermissionOffer(url, AccessLevel.WRITE); pm.makeOffer(offer, new PermissionManager.MakeOfferCallback() { @Override public void onSuccess(String offerToken) { assertNotNull(offerToken); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void makeOffer_noManageAccessThrows() { // User 2 creates a Realm SyncUser user2 = UserFactory.createUniqueUser(); String url = createRemoteRealm(user2, "test"); // User 1 tries to create an offer for it. PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); PermissionOffer offer = new PermissionOffer(url, AccessLevel.WRITE); pm.makeOffer(offer, new PermissionManager.MakeOfferCallback() { @Override public void onSuccess(String offerToken) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.ACCESS_DENIED, error.getErrorCode()); looperThread.testComplete(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void acceptOffer() { final String offerToken = createOffer(user, "test", AccessLevel.WRITE, null); final SyncUser user2 = UserFactory.createUniqueUser(); final PermissionManager pm = user2.getPermissionManager(); looperThread.closeAfterTest(pm); pm.acceptOffer(offerToken, new PermissionManager.AcceptOfferCallback() { @Override public void onSuccess(String url, Permission permission) { assertEquals("/" + user.getIdentity() + "/test", permission.getPath()); assertTrue(permission.mayRead()); assertTrue(permission.mayWrite()); assertFalse(permission.mayManage()); assertEquals(user2.getIdentity(), permission.getUserId()); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void acceptOffer_invalidToken() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.acceptOffer("wrong-token", new PermissionManager.AcceptOfferCallback() { @Override public void onSuccess(String url, Permission permission) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.INVALID_PARAMETERS, error.getErrorCode()); looperThread.testComplete(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) @Ignore("The offer is randomly accepted mostly on docker-02 SHIELD K1") public void acceptOffer_expiredThrows() { // Trying to guess how long CI is to process this. The offer cannot be created if it // already expired. long delayMillis = TimeUnit.SECONDS.toMillis(10); Date expiresAt = new Date(new Date().getTime() + delayMillis); final String offerToken = createOffer(user, "test", AccessLevel.WRITE, expiresAt); SystemClock.sleep(delayMillis); // Make sure that the offer expires. final SyncUser user2 = UserFactory.createUniqueUser(); final PermissionManager pm = user2.getPermissionManager(); looperThread.closeAfterTest(pm); pm.acceptOffer(offerToken, new PermissionManager.AcceptOfferCallback() { @Override public void onSuccess(String url, Permission permission) { fail(); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.EXPIRED_PERMISSION_OFFER, error.getErrorCode()); looperThread.testComplete(); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void acceptOffer_multipleUsers() { final String offerToken = createOffer(user, "test", AccessLevel.WRITE, null); final SyncUser user2 = UserFactory.createUniqueUser(); final SyncUser user3 = UserFactory.createUniqueUser(); final PermissionManager pm2 = user2.getPermissionManager(); final PermissionManager pm3 = user3.getPermissionManager(); looperThread.closeAfterTest(pm2); looperThread.closeAfterTest(pm3); final AtomicInteger offersAccepted = new AtomicInteger(0); PermissionManager.AcceptOfferCallback callback = new PermissionManager.AcceptOfferCallback() { @Override public void onSuccess(String url, Permission permission) { assertEquals("/" + user.getIdentity() + "/test", permission.getPath()); assertTrue(permission.mayRead()); assertTrue(permission.mayWrite()); assertFalse(permission.mayManage()); if (offersAccepted.incrementAndGet() == 2) { looperThread.testComplete(); } } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }; pm2.acceptOffer(offerToken, callback); pm3.acceptOffer(offerToken, callback); } @Test @RunTestInLooperThread(emulateMainThread = true) public void getCreatedOffers() { final String offerToken = createOffer(user, "test", AccessLevel.WRITE, null); PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getCreatedOffers(new PermissionManager.OffersCallback() { @Override public void onSuccess(RealmResults<PermissionOffer> offers) { RealmResults filteredOffers = offers.where() .equalTo("token", offerToken) .findAllAsync(); looperThread.keepStrongReference(offers); filteredOffers.addChangeListener(new RealmChangeListener<RealmResults>() { @Override public void onChange(RealmResults results) { switch (results.size()) { case 0: return; case 1: looperThread.testComplete(); break; default: fail("To many offers: " + Arrays.toString(results.toArray())); } } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void revokeOffer() { // createOffer validates that the offer is actually in the __management Realm. final String offerToken = createOffer(user, "test", AccessLevel.WRITE, null); final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.revokeOffer(offerToken, new PermissionManager.RevokeOfferCallback() { @Override public void onSuccess() { pm.getCreatedOffers(new PermissionManager.OffersCallback() { @Override public void onSuccess(RealmResults<PermissionOffer> offers) { assertEquals(0, offers.size()); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) public void revokeOffer_afterOneAcceptEdit() { // createOffer validates that the offer is actually in the __management Realm. final String offerToken = createOffer(user, "test", AccessLevel.WRITE, null); SyncUser user2 = UserFactory.createUniqueUser(); SyncUser user3 = UserFactory.createUniqueUser(); final PermissionManager pm1 = user.getPermissionManager(); PermissionManager pm2 = user2.getPermissionManager(); final PermissionManager pm3 = user3.getPermissionManager(); looperThread.closeAfterTest(pm1); looperThread.closeAfterTest(pm2); looperThread.closeAfterTest(pm3); pm2.acceptOffer(offerToken, new PermissionManager.AcceptOfferCallback() { @Override public void onSuccess(String realmUrl, Permission permission) { pm1.revokeOffer(offerToken, new PermissionManager.RevokeOfferCallback() { @Override public void onSuccess() { pm3.acceptOffer(offerToken, new PermissionManager.AcceptOfferCallback() { @Override public void onSuccess(String realmUrl, Permission permission) { fail("Offer should have been revoked"); } @Override public void onError(ObjectServerError error) { assertEquals(ErrorCode.INVALID_PARAMETERS, error.getErrorCode()); looperThread.testComplete(); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); } @Test @RunTestInLooperThread(emulateMainThread = true) @Ignore("Figure out why clocks on server/emulator on CI seem to differ") public void revokeOffer_alreadyExpired() { fail("Implement this"); } /** * Creates a offer for a newly created Realm. * * @param user User that should create the offer * @param realmName Realm to create * @param level accessLevel to offer * @param expires when the offer expires */ private String createOffer(final SyncUser user, final String realmName, final AccessLevel level, final Date expires) { final CountDownLatch offerReady = new CountDownLatch(1); final AtomicReference<String> offer = new AtomicReference<>(null); final HandlerThread ht = new HandlerThread("OfferThread"); ht.start(); Handler handler = new Handler(ht.getLooper()); handler.post(new Runnable() { @Override public void run() { String url = createRemoteRealm(user, realmName); final PermissionManager pm = user.getPermissionManager(); pm.makeOffer(new PermissionOffer(url, level, expires), new PermissionManager.MakeOfferCallback() { @Override public void onSuccess(String offerToken) { offer.set(offerToken); pm.close(); offerReady.countDown(); } @Override public void onError(ObjectServerError error) { pm.close(); fail(error.toString()); } }); } }); TestHelper.awaitOrFail(offerReady); ht.quit(); return offer.get(); } /** * Wait for a given permission to be present. * * @param permissions permission results. * @param user user that is being granted the permission. * @param urlSuffix the url suffix to listen for. * @param accessLevel the expected access level for 'user'. */ private void assertPermissionPresent(RealmResults<Permission> permissions, final SyncUser user, String urlSuffix, final AccessLevel accessLevel) { RealmResults<Permission> filteredPermissions = permissions.where().endsWith("path", urlSuffix).findAllAsync(); looperThread.keepStrongReference(permissions); filteredPermissions.addChangeListener(new RealmChangeListener<RealmResults<Permission>>() { @Override public void onChange(RealmResults<Permission> permissions) { switch(permissions.size()) { case 0: return; case 1: Permission p = permissions.first(); assertEquals(accessLevel.mayRead(), p.mayRead()); assertEquals(accessLevel.mayWrite(), p.mayWrite()); assertEquals(accessLevel.mayManage(), p.mayManage()); assertEquals(user.getIdentity(), p.getUserId()); looperThread.testComplete(); break; default: fail("To many permissions matched: " + Arrays.toString(permissions.toArray())); } } }); } private void setRealmError(PermissionManager pm, String fieldName, ObjectServerError error) throws NoSuchFieldException, IllegalAccessException { Field managementRealmErrorField = pm.getClass().getDeclaredField(fieldName); managementRealmErrorField.setAccessible(true); managementRealmErrorField.set(pm, error); } private void runTask(final PermissionManager pm, final PermissionManager.ApplyPermissionsCallback callback) { new PermissionManager.PermissionManagerTask<Void>(pm, callback) { @Override public void run() { if (!checkAndReportInvalidState()) { fail(); } } }.run(); } /** * Creates an empty remote Realm on ROS owned by the provided user */ private String createRemoteRealm(SyncUser user, String realmName) { String url = Constants.AUTH_SERVER_URL + "~/" + realmName; SyncConfiguration config = new SyncConfiguration.Builder(user, url) .name(realmName) .sessionStopPolicy(OsRealmConfig.SyncSessionStopPolicy.IMMEDIATELY) .build(); Realm realm = Realm.getInstance(config); SyncSession session = SyncManager.getSession(config); final CountDownLatch uploadLatch = new CountDownLatch(1); session.addUploadProgressListener(ProgressMode.CURRENT_CHANGES, new ProgressListener() { @Override public void onChange(Progress progress) { if (progress.isTransferComplete()) { uploadLatch.countDown(); } } }); TestHelper.awaitOrFail(uploadLatch); realm.close(); return config.getServerUrl().toString(); } /** * The initial set of permissions of ROS is timing dependant. This method will identify the possible known starting * states and fail if neither of these can be verified. */ private void assertInitialPermissions(RealmResults<Permission> permissions) { assertEquals("Unexpected count() for __permission Realm: " + Arrays.toString(permissions.toArray()), 1, permissions.where().endsWith("path", "__permission").count()); assertEquals("Unexpected count() for __management Realm: " + Arrays.toString(permissions.toArray()), 1, permissions.where().endsWith("path", "__management").count()); } private void assertInitialDefaultPermissions(RealmResults<Permission> permissions) { assertEquals("Unexpected count() for __wildcardpermissions Realm: " + Arrays.toString(permissions.toArray()), 1, permissions.where().endsWith("path", "__wildcardpermissions").count()); } private void assertGreaterThan(String error, int base, long count) { if (count <= base) { throw new AssertionError(error); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jini.jeri.http; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.HashMap; import java.util.Map; import net.jini.core.constraint.ClientAuthentication; import net.jini.core.constraint.ClientMaxPrincipal; import net.jini.core.constraint.ClientMaxPrincipalType; import net.jini.core.constraint.ClientMinPrincipal; import net.jini.core.constraint.ClientMinPrincipalType; import net.jini.core.constraint.Confidentiality; import net.jini.core.constraint.ConnectionAbsoluteTime; import net.jini.core.constraint.ConnectionRelativeTime; import net.jini.core.constraint.ConstraintAlternatives; import net.jini.core.constraint.Delegation; import net.jini.core.constraint.DelegationAbsoluteTime; import net.jini.core.constraint.DelegationRelativeTime; import net.jini.core.constraint.Integrity; import net.jini.core.constraint.InvocationConstraint; import net.jini.core.constraint.InvocationConstraints; import net.jini.core.constraint.RelativeTimeConstraint; import net.jini.core.constraint.ServerAuthentication; import net.jini.core.constraint.ServerMinPrincipal; import net.jini.io.UnsupportedConstraintException; /** * Constraint support for this transport provider. * * This code makes some significant simplifying assumptions: * * - The transport layer aspects of all constraints supported by this * provider are always satisfied by all open connections and * requests. * * - No combination of individual constraints supported by this * provider can contain conflicting constraints. * * @author Sun Microsystems, Inc. **/ class Constraints { /** * indicates that this provider does not support implementing (or * does not understand how to implement) the transport layer * aspects of satisfying a given constraint **/ private static final int NO_SUPPORT = 0; /** * indicates that this provider supports implementing all aspects * of satisfying a given constraint **/ private static final int FULL_SUPPORT = 1; /** * indicates that this provider supports implementing the * transport layer aspects of satisfying a given constraint, but * at least partial implementation by higher layers is also needed * in order to fully satisfy the constraint **/ private static final int PARTIAL_SUPPORT = 2; /** * maps constraint values that are supported to Boolean indicating * whether or not they must be at least partially implemented by * higher layers to be fully satisfied **/ private static final Map supportedValues = new HashMap(); static { supportedValues.put(Integrity.NO, Boolean.TRUE); supportedValues.put(Confidentiality.NO, Boolean.FALSE); supportedValues.put(ClientAuthentication.NO, Boolean.FALSE); supportedValues.put(ServerAuthentication.NO, Boolean.FALSE); supportedValues.put(Delegation.NO, Boolean.FALSE); } /** * maps constraint classes that are supported to Boolean * indicating whether or not such constraints must be at least * partially implemented by higher layers to be fully satisfied **/ private static final Map supportedClasses = new HashMap(); static { // ConstraintAlternatives is supported but handled specially in code supportedClasses.put(ConnectionAbsoluteTime.class, Boolean.FALSE); supportedClasses.put(ConnectionRelativeTime.class, Boolean.FALSE); /* * The following classes are (trivially) supported just * because ClientAuthentication.YES, ServerAuthentication.YES, * and Delegation.YES are not supported. */ supportedClasses.put(ClientMaxPrincipal.class, Boolean.FALSE); supportedClasses.put(ClientMaxPrincipalType.class, Boolean.FALSE); supportedClasses.put(ClientMinPrincipal.class, Boolean.FALSE); supportedClasses.put(ClientMinPrincipalType.class, Boolean.FALSE); supportedClasses.put(ServerMinPrincipal.class, Boolean.FALSE); supportedClasses.put(DelegationAbsoluteTime.class, Boolean.FALSE); supportedClasses.put(DelegationRelativeTime.class, Boolean.FALSE); } /** * Returns this provider's general support for the given * constraint. **/ private static int getSupport(InvocationConstraint c) { Boolean support = (Boolean) supportedValues.get(c); if (support == null) { support = (Boolean) supportedClasses.get(c.getClass()); } return support == null ? NO_SUPPORT : support.booleanValue() ? PARTIAL_SUPPORT : FULL_SUPPORT; } /** * Checks that we support at least the transport layer aspects of * the given requirements (and throws an * UnsupportedConstraintException if not), and returns the * requirements that must be at least partially implemented by * higher layers and the supported preferences that must be at * least partially implemented by higher layers. * * [If this provider supported constraints whose transport layer * aspects were not always satisfied by open connections or * requests, then we would need a variant of this method that * checks the given constraints against an open connection or * request. If this provider supported constraints that could * conflict with each other then (when not checking against an * open connection or request) we would need to check for possible * conflicts.] **/ static InvocationConstraints check(InvocationConstraints constraints, boolean relativeOK) throws UnsupportedConstraintException { return distill(constraints, relativeOK).getUnfulfilledConstraints(); } /** * Distills the given constraints to a form more directly usable * by this provider. Throws an UnsupportedConstraintException if * we do not support at least the transport layer aspects of the * requirements. **/ static Distilled distill(InvocationConstraints constraints, boolean relativeOK) throws UnsupportedConstraintException { return new Distilled(constraints, relativeOK); } private Constraints() { throw new AssertionError(); } /** * A distillation of constraints to a form more directly usable by * this provider. **/ static class Distilled { /** * true if relative time constraints are allowed (in other * words, not for client-side use) */ private final boolean relativeOK; private Collection unfulfilledRequirements = null; // lazily created private Collection unfulfilledPreferences = null; // lazily created private boolean hasConnectDeadline = false; private long connectDeadline; Distilled(InvocationConstraints constraints, boolean relativeOK) throws UnsupportedConstraintException { this.relativeOK = relativeOK; for (Iterator i = constraints.requirements().iterator(); i.hasNext();) { addConstraint((InvocationConstraint) i.next(), true); } for (Iterator i = constraints.preferences().iterator(); i.hasNext();) { addConstraint((InvocationConstraint) i.next(), false); } } /** * Returns the requirements and supported preferences that * must be at least partially implemented by higher layers. **/ InvocationConstraints getUnfulfilledConstraints() { if (unfulfilledRequirements == null && unfulfilledPreferences == null) { return InvocationConstraints.EMPTY; } else { return new InvocationConstraints(unfulfilledRequirements, unfulfilledPreferences); } } /** * Returns true if a there is a socket connect deadline. **/ boolean hasConnectDeadline() { return hasConnectDeadline; } /** * Returns the absolute time of the socket connect deadline. **/ long getConnectDeadline() { assert hasConnectDeadline; return connectDeadline; } /** * If "isRequirement" is true, throws an * UnsupportedConstraintException if we do not support at * least the transport layer aspects of the given constraint. * * If we do support at least the transport layer aspects of * the given constraint, then if appropriate, adds it to the * collection of requirements or preferences that must be at * least partially implemented by higher layers. **/ private void addConstraint(InvocationConstraint constraint, boolean isRequirement) throws UnsupportedConstraintException { if (!(constraint instanceof ConstraintAlternatives)) { int support = getSupport(constraint); if (support == NO_SUPPORT || (!relativeOK && constraint instanceof RelativeTimeConstraint)) { if (isRequirement) { throw new UnsupportedConstraintException( "cannot satisfy constraint: " + constraint); } else { return; } } if (support == PARTIAL_SUPPORT) { if (isRequirement) { if (unfulfilledRequirements == null) { unfulfilledRequirements = new ArrayList(); } unfulfilledRequirements.add(constraint); } else { if (unfulfilledPreferences == null) { unfulfilledPreferences = new ArrayList(); } unfulfilledPreferences.add(constraint); } } if (constraint instanceof ConnectionAbsoluteTime) { // REMIND: only bother with this on client side? addConnectDeadline( ((ConnectionAbsoluteTime) constraint).getTime()); } } else { addAlternatives((ConstraintAlternatives) constraint, isRequirement); } } /** * If "isRequirement" is true, throws an * UnsupportedConstraintException if we do not support at * least the transport layer aspects of at least one of the * constraints in the given alternatives. * * If we do support at least the transport layer aspects of at * least one of the constraints in the given alternatives, * then if appropriate, adds a ConstraintAlternatives of the * supported alternatives to the collection of requirements or * preferences that must be at least partially implemented by * higher layers. * * If all of the supported alternatives need at least partial * implementation by higher layers, then adds a * ConstraintAlternatives with all of the supported * alternatives to the unfulfilled collection or preferences, * because higher layers must support at least one of them. * But if at least one of the supported alternatives can be * fully satisfied by the transport layer, then add nothing to * the unfulfilled collection, because it is possible that * higher layers need not support any of them (and there is no * way to express no constraint). * * The weakest connect deadline (with no deadline being the * the weakest possibility) is chosen among alternatives. **/ private void addAlternatives(ConstraintAlternatives constraint, boolean isRequirement) throws UnsupportedConstraintException { Collection alts = constraint.elements(); boolean supported = false; long maxConnectDeadline = Long.MIN_VALUE; Collection unfulfilledAlts = null; // lazily created boolean forgetUnfulfilled = false; for (Iterator i = alts.iterator(); i.hasNext();) { InvocationConstraint c = (InvocationConstraint) i.next(); // nested ConstraintAlternatives not allowed int support = getSupport(c); if (support == NO_SUPPORT || (!relativeOK && c instanceof RelativeTimeConstraint)) { continue; } supported = true; // we support at least one if (!forgetUnfulfilled) { if (support == PARTIAL_SUPPORT) { if (unfulfilledAlts == null) { unfulfilledAlts = new ArrayList(); } unfulfilledAlts.add(c); } else { assert support == FULL_SUPPORT; unfulfilledAlts = null; forgetUnfulfilled = true; } } if (c instanceof ConnectionAbsoluteTime) { assert support == FULL_SUPPORT; // else more care required maxConnectDeadline = Math.max(maxConnectDeadline, ((ConnectionAbsoluteTime) c).getTime()); } else { maxConnectDeadline = Long.MAX_VALUE; } } if (!supported) { if (isRequirement) { throw new UnsupportedConstraintException( "cannot satisfy constraint: " + constraint); } else { return; // maxConnectDeadline is bogus in this case } } if (!forgetUnfulfilled && unfulfilledAlts != null) { if (isRequirement) { if (unfulfilledRequirements == null) { unfulfilledRequirements = new ArrayList(); } unfulfilledRequirements.add( ConstraintAlternatives.create(unfulfilledAlts)); } else { if (unfulfilledPreferences == null) { unfulfilledPreferences = new ArrayList(); } unfulfilledPreferences.add( ConstraintAlternatives.create(unfulfilledAlts)); } } if (maxConnectDeadline < Long.MAX_VALUE) { assert maxConnectDeadline != Long.MIN_VALUE; addConnectDeadline(maxConnectDeadline); } } /** * Adds the given connect deadline to this object's state. * The earliest connect deadline is what gets remembered. **/ private void addConnectDeadline(long deadline) { if (!hasConnectDeadline) { hasConnectDeadline = true; connectDeadline = deadline; } else { connectDeadline = Math.min(connectDeadline, deadline); } } } }
/* * Copyright 1997-2015 Optimatika (www.optimatika.se) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.array; import static org.ojalgo.constant.PrimitiveMath.*; import java.lang.reflect.Field; import java.util.Iterator; import org.ojalgo.access.Access1D; import org.ojalgo.access.AccessUtils; import org.ojalgo.constant.PrimitiveMath; import org.ojalgo.function.BinaryFunction; import org.ojalgo.function.NullaryFunction; import org.ojalgo.function.UnaryFunction; import org.ojalgo.function.VoidFunction; import org.ojalgo.machine.JavaType; import org.ojalgo.scalar.PrimitiveScalar; import sun.misc.Unsafe; /** * Off heap memory array. * * @author apete */ public final class OffHeapArray extends BasicArray<Double> { static final ArrayFactory<Double> FACTORY = new ArrayFactory<Double>() { @Override long getElementSize() { return JavaType.DOUBLE.memory(); } @Override BasicArray<Double> makeStructuredZero(final long... structure) { return new OffHeapArray(AccessUtils.count(structure)); } @Override BasicArray<Double> makeToBeFilled(final long... structure) { return new OffHeapArray(AccessUtils.count(structure)); } }; static Unsafe UNSAFE; static { Unsafe tmpUnsafe = null; try { final Field tmpField = Unsafe.class.getDeclaredField("theUnsafe"); tmpField.setAccessible(true); tmpUnsafe = (Unsafe) tmpField.get(null); } catch (final Exception e) { tmpUnsafe = null; } finally { UNSAFE = tmpUnsafe; } } public static OffHeapArray make(final long count) { return new OffHeapArray(count); } public static final SegmentedArray<Double> makeSegmented(final long count) { return SegmentedArray.make(FACTORY, count); } private final long data; private final long myCount; OffHeapArray(final long count) { super(); myCount = count; data = UNSAFE.allocateMemory(Unsafe.ARRAY_DOUBLE_INDEX_SCALE * count); this.fillAll(PrimitiveMath.ZERO); } public long count() { return myCount; } public double doubleValue(final long index) { return UNSAFE.getDouble(this.address(index)); } public void fillAll(final Double value) { this.fill(0L, myCount, 1L, value); } public void fillAll(final NullaryFunction<Double> supplier) { // TODO Auto-generated method stub } public void fillRange(final long first, final long limit, final Double value) { this.fill(first, limit, 1L, value); } public void fillRange(final long first, final long limit, final NullaryFunction<Double> supplier) { // TODO Auto-generated method stub } public Double get(final long index) { return UNSAFE.getDouble(this.address(index)); } public boolean isAbsolute(final long index) { return PrimitiveScalar.isAbsolute(UNSAFE.getDouble(this.address(index))); } public boolean isSmall(final long index, final double comparedTo) { return PrimitiveScalar.isSmall(UNSAFE.getDouble(this.address(index)), comparedTo); } public Iterator<Double> iterator() { // TODO Auto-generated method stub return null; } public void modifyOne(final long index, final UnaryFunction<Double> function) { // TODO Auto-generated method stub } public void set(final long index, final double value) { UNSAFE.putDouble(this.address(index), value); } public void set(final long index, final Number value) { UNSAFE.putDouble(this.address(index), value.doubleValue()); } private final long address(final long index) { return data + (index * Unsafe.ARRAY_DOUBLE_INDEX_SCALE); } private final long increment(final long step) { return step * Unsafe.ARRAY_DOUBLE_INDEX_SCALE; } @Override protected void exchange(final long firstA, final long firstB, final long step, final long count) { long tmpIndexA = firstA; long tmpIndexB = firstB; double tmpVal; for (long i = 0; i < count; i++) { tmpVal = this.doubleValue(tmpIndexA); this.set(tmpIndexA, this.doubleValue(tmpIndexB)); this.set(tmpIndexB, tmpVal); tmpIndexA += step; tmpIndexB += step; } } @Override protected void fill(final long first, final long limit, final long step, final Double value) { final long tmpFirst = this.address(first); final long tmpLimit = this.address(limit); final long tmpStep = this.increment(step); final double tmpValue = value.doubleValue(); for (long a = tmpFirst; a < tmpLimit; a += tmpStep) { UNSAFE.putDouble(a, tmpValue); } } @Override protected void fill(final long first, final long limit, final long step, final NullaryFunction<Double> supplier) { // TODO Auto-generated method stub } @Override protected void finalize() throws Throwable { UNSAFE.freeMemory(data); } @Override protected long indexOfLargest(final long first, final long limit, final long step) { long retVal = first; double tmpLargest = ZERO; double tmpValue; for (long i = first; i < limit; i += step) { tmpValue = Math.abs(this.doubleValue(i)); if (tmpValue > tmpLargest) { tmpLargest = tmpValue; retVal = i; } } return retVal; } @Override protected boolean isSmall(final long first, final long limit, final long step, final double comparedTo) { boolean retVal = true; for (long i = first; retVal && (i < limit); i += step) { retVal &= PrimitiveScalar.isSmall(comparedTo, this.doubleValue(i)); } return retVal; } @Override protected void modify(final long first, final long limit, final long step, final Access1D<Double> left, final BinaryFunction<Double> function) { long tmpAddress; for (long i = first; i < limit; i += step) { tmpAddress = this.address(i); UNSAFE.putDouble(tmpAddress, function.invoke(left.doubleValue(i), UNSAFE.getDouble(tmpAddress))); } } @Override protected void modify(final long first, final long limit, final long step, final BinaryFunction<Double> function, final Access1D<Double> right) { long tmpAddress; for (long i = first; i < limit; i += step) { tmpAddress = this.address(i); UNSAFE.putDouble(tmpAddress, function.invoke(UNSAFE.getDouble(tmpAddress), right.doubleValue(i))); } } @Override protected void modify(final long first, final long limit, final long step, final UnaryFunction<Double> function) { final long tmpFirst = this.address(first); final long tmpLimit = this.address(limit); final long tmpStep = this.increment(step); for (long a = tmpFirst; a < tmpLimit; a += tmpStep) { UNSAFE.putDouble(a, function.invoke(UNSAFE.getDouble(a))); } } @Override protected void visit(final long first, final long limit, final long step, final VoidFunction<Double> visitor) { final long tmpFirst = this.address(first); final long tmpLimit = this.address(limit); final long tmpStep = this.increment(step); for (long a = tmpFirst; a < tmpLimit; a += tmpStep) { visitor.invoke(UNSAFE.getDouble(a)); } } @Override boolean isPrimitive() { return true; } public void fillOne(final long index, final Double value) { // TODO Auto-generated method stub } public void fillOne(final long index, final NullaryFunction<Double> supplier) { // TODO Auto-generated method stub } public void add(final long index, final double addend) { // TODO Auto-generated method stub } public void add(final long index, final Number addend) { // TODO Auto-generated method stub } public void visitOne(final long index, final VoidFunction<Double> visitor) { // TODO Auto-generated method stub } }
package juego; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import cliente.Cliente; import cliente.EnviadorPosicion; import item.ItemEquipo; import mapa.Punto; import mapagrafico.MapaGrafico; import mapagrafico.TileCofre; import musica.AudioFilePlayer; import personaje.Personaje; import tiles.TilePersonajeLocal; import tiles.TilePersonajeRemoto; import ventana.CombatButton; @SuppressWarnings("serial") public class JuegoPanel extends Component implements Runnable{ public static final int ANCHO = 800; public static final int ALTO = 600; public static final int fps = 60; public static double timePerTick = 1000000000/fps; protected JFrame padre; protected Opciones opciones; protected Cliente cliente; protected EnviadorPosicion env; private MapaGrafico mapa; private Thread thread; private Mouse mouse; private double delta = 0; private boolean ejecutando = true; private TilePersonajeLocal pjDibujo; private Camara camara; private HashMap<String, TilePersonajeRemoto> personajes; private HashMap<String, TileCofre > itemEquipo; AudioFilePlayer playerMusic; private boolean jugar = true; public JuegoPanel(JFrame padre,Punto spaw, Personaje pj,String nombreMapa, Cliente cliente) { this.padre = padre; this.cliente = cliente; this.personajes = new HashMap<String, TilePersonajeRemoto>(); this.itemEquipo = new HashMap<String, TileCofre>(); env = new EnviadorPosicion(cliente, pj.getNombre(),nombreMapa, pj.getSprite()); setPreferredSize(new Dimension(ANCHO, ALTO)); setFocusable(true); requestFocus(); opciones = new Opciones(pj,cliente); mouse = new Mouse(); camara = new Camara(ANCHO, ALTO); addMouseListener(mouse); pjDibujo = new TilePersonajeLocal(spaw,pj,mouse,camara); mapa = new MapaGrafico(nombreMapa,pjDibujo,camara, env,personajes,itemEquipo); playerMusic = new AudioFilePlayer ("src/main/resources/sound/mapsong2.ogg",80,true); playerMusic.start(); thread = new Thread(this); thread.start(); } @Override public void run(){ long now; long lastTime = System.nanoTime(); long primeravez = System.nanoTime(); while(ejecutando) { now = System.nanoTime(); delta += (now - lastTime)/timePerTick; lastTime = now; if(delta >=1){ actualizar(); repaint(); delta--; } } } public void actualizar() { mouse.actualizar(); pjDibujo.actualizar(); mapa.actualizar(); mouseInteracion(); } private void mouseInteracion() { if(mouse.isInteraccion()){ String alguien = hayAlguien(mouse.getPosInt()); if(alguien != null) cliente.enviarMensajeCombate(alguien); String itemE = hayAlgo(mouse.getPosInt()); if(itemE != null){ itemEquipo.get(itemE).abrir(); cliente.pedirItem(itemE); } mouse.setInteraccion(false); } if(mouse.isMenu()){ opciones.setVisible(true); mouse.setMenu(false); } } private String hayAlguien(Punto posInt) { int deltaX = posInt.getX() - camara.getxOffCamara() + camara.getxActualPJ(); int deltaY = posInt.getY() - camara.getyOffCamara() + camara.getyActualPJ(); for (String persona : personajes.keySet()) { int x = personajes.get(persona).getXDestino(); int y = personajes.get(persona).getYDestino(); if(x==deltaX && y == deltaY) return persona; } return null; } private String hayAlgo(Punto posInt) { int deltaX = posInt.getX() - camara.getxOffCamara() + camara.getxActualPJ(); int deltaY = posInt.getY() - camara.getyOffCamara() + camara.getyActualPJ(); for (String itemE : itemEquipo.keySet()) { int x = itemEquipo.get(itemE).getX(); int y = itemEquipo.get(itemE).getY(); if(x==deltaX && y == deltaY){ mapa.cambiarSprite(x,y,5); return itemE; } } return null; } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D) g; if(jugar){ mapa.dibujar(g2d); jugar = false; } mapa.mover(g2d); } public void nuevoMovimientoPersonajes(String pj, String sprite, Punto point){ TilePersonajeRemoto player = personajes.get(pj); if (player == null){ player= new TilePersonajeRemoto(pj,sprite,point, camara); personajes.put(pj, player ); repaint(); } else{ mapa.moverPlayer(player,point); } } public void nuevaDetencionPersonaje(String pj){ //estp creo que vuela. // aca te envio que el personaje llego a su destino, // si por las dudas no llego todavia moverlo magicamente. } public void detener() { ejecutando = false; playerMusic.detener(); } public void quitarPersonaje(String emisor) { personajes.remove(emisor); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.classification; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.WildcardQuery; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefBuilder; import org.apache.lucene.util.IntsRefBuilder; import org.apache.lucene.util.fst.Builder; import org.apache.lucene.util.fst.FST; import org.apache.lucene.util.fst.PositiveIntOutputs; import org.apache.lucene.util.fst.Util; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; /** * A perceptron (see <code>http://en.wikipedia.org/wiki/Perceptron</code>) based * <code>Boolean</code> {@link org.apache.lucene.classification.Classifier}. The * weights are calculated using * {@link org.apache.lucene.index.TermsEnum#totalTermFreq} both on a per field * and a per document basis and then a corresponding * {@link org.apache.lucene.util.fst.FST} is used for class assignment. * * @lucene.experimental */ public class BooleanPerceptronClassifier implements Classifier<Boolean> { private Double threshold; private final Integer batchSize; private Terms textTerms; private Analyzer analyzer; private String textFieldName; private FST<Long> fst; /** * Create a {@link BooleanPerceptronClassifier} * * @param threshold * the binary threshold for perceptron output evaluation */ public BooleanPerceptronClassifier(Double threshold, Integer batchSize) { this.threshold = threshold; this.batchSize = batchSize; } /** * Default constructor, no batch updates of FST, perceptron threshold is * calculated via underlying index metrics during * {@link #train(org.apache.lucene.index.LeafReader, String, String, org.apache.lucene.analysis.Analyzer) * training} */ public BooleanPerceptronClassifier() { batchSize = 1; } /** * {@inheritDoc} */ @Override public ClassificationResult<Boolean> assignClass(String text) throws IOException { if (textTerms == null) { throw new IOException("You must first call Classifier#train"); } Long output = 0l; try (TokenStream tokenStream = analyzer.tokenStream(textFieldName, text)) { CharTermAttribute charTermAttribute = tokenStream .addAttribute(CharTermAttribute.class); tokenStream.reset(); while (tokenStream.incrementToken()) { String s = charTermAttribute.toString(); Long d = Util.get(fst, new BytesRef(s)); if (d != null) { output += d; } } tokenStream.end(); } return new ClassificationResult<>(output >= threshold, output.doubleValue()); } /** * {@inheritDoc} */ @Override public void train(LeafReader leafReader, String textFieldName, String classFieldName, Analyzer analyzer) throws IOException { train(leafReader, textFieldName, classFieldName, analyzer, null); } /** * {@inheritDoc} */ @Override public void train(LeafReader leafReader, String textFieldName, String classFieldName, Analyzer analyzer, Query query) throws IOException { this.textTerms = MultiFields.getTerms(leafReader, textFieldName); if (textTerms == null) { throw new IOException("term vectors need to be available for field " + textFieldName); } this.analyzer = analyzer; this.textFieldName = textFieldName; if (threshold == null || threshold == 0d) { // automatic assign a threshold long sumDocFreq = leafReader.getSumDocFreq(textFieldName); if (sumDocFreq != -1) { this.threshold = (double) sumDocFreq / 2d; } else { throw new IOException( "threshold cannot be assigned since term vectors for field " + textFieldName + " do not exist"); } } // TODO : remove this map as soon as we have a writable FST SortedMap<String,Double> weights = new TreeMap<>(); TermsEnum termsEnum = textTerms.iterator(); BytesRef textTerm; while ((textTerm = termsEnum.next()) != null) { weights.put(textTerm.utf8ToString(), (double) termsEnum.totalTermFreq()); } updateFST(weights); IndexSearcher indexSearcher = new IndexSearcher(leafReader); int batchCount = 0; BooleanQuery q = new BooleanQuery(); q.add(new BooleanClause(new WildcardQuery(new Term(classFieldName, "*")), BooleanClause.Occur.MUST)); if (query != null) { q.add(new BooleanClause(query, BooleanClause.Occur.MUST)); } // run the search and use stored field values for (ScoreDoc scoreDoc : indexSearcher.search(q, Integer.MAX_VALUE).scoreDocs) { Document doc = indexSearcher.doc(scoreDoc.doc); IndexableField textField = doc.getField(textFieldName); // get the expected result IndexableField classField = doc.getField(classFieldName); if (textField != null && classField != null) { // assign class to the doc ClassificationResult<Boolean> classificationResult = assignClass(textField.stringValue()); Boolean assignedClass = classificationResult.getAssignedClass(); Boolean correctClass = Boolean.valueOf(classField.stringValue()); long modifier = correctClass.compareTo(assignedClass); if (modifier != 0) { updateWeights(leafReader, scoreDoc.doc, assignedClass, weights, modifier, batchCount % batchSize == 0); } batchCount++; } } weights.clear(); // free memory while waiting for GC } @Override public void train(LeafReader leafReader, String[] textFieldNames, String classFieldName, Analyzer analyzer, Query query) throws IOException { throw new IOException("training with multiple fields not supported by boolean perceptron classifier"); } private void updateWeights(LeafReader leafReader, int docId, Boolean assignedClass, SortedMap<String, Double> weights, double modifier, boolean updateFST) throws IOException { TermsEnum cte = textTerms.iterator(); // get the doc term vectors Terms terms = leafReader.getTermVector(docId, textFieldName); if (terms == null) { throw new IOException("term vectors must be stored for field " + textFieldName); } TermsEnum termsEnum = terms.iterator(); BytesRef term; while ((term = termsEnum.next()) != null) { cte.seekExact(term); if (assignedClass != null) { long termFreqLocal = termsEnum.totalTermFreq(); // update weights Long previousValue = Util.get(fst, term); String termString = term.utf8ToString(); weights.put(termString, previousValue + modifier * termFreqLocal); } } if (updateFST) { updateFST(weights); } } private void updateFST(SortedMap<String,Double> weights) throws IOException { PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton(); Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs); BytesRefBuilder scratchBytes = new BytesRefBuilder(); IntsRefBuilder scratchInts = new IntsRefBuilder(); for (Map.Entry<String,Double> entry : weights.entrySet()) { scratchBytes.copyChars(entry.getKey()); fstBuilder.add(Util.toIntsRef(scratchBytes.get(), scratchInts), entry .getValue().longValue()); } fst = fstBuilder.finish(); } /** * {@inheritDoc} */ @Override public List<ClassificationResult<Boolean>> getClasses(String text) throws IOException { throw new RuntimeException("not implemented"); } /** * {@inheritDoc} */ @Override public List<ClassificationResult<Boolean>> getClasses(String text, int max) throws IOException { throw new RuntimeException("not implemented"); } }
package org.wikipedia.dataclient; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.wikipedia.json.GsonMarshaller; import org.wikipedia.json.GsonUnmarshaller; import org.wikipedia.page.PageTitle; import org.wikipedia.test.TestParcelUtil; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; @RunWith(RobolectricTestRunner.class) public class WikiSiteTest { @Test public void testSupportedAuthority() { assertThat(WikiSite.supportedAuthority("fr.wikipedia.org"), is(true)); assertThat(WikiSite.supportedAuthority("fr.m.wikipedia.org"), is(true)); assertThat(WikiSite.supportedAuthority("roa-rup.wikipedia.org"), is(true)); assertThat(WikiSite.supportedAuthority("google.com"), is(false)); } @Test public void testForLanguageCodeScheme() { WikiSite subject = WikiSite.forLanguageCode("test"); assertThat(subject.scheme(), is("https")); } @Test public void testForLanguageCodeAuthority() { WikiSite subject = WikiSite.forLanguageCode("test"); assertThat(subject.authority(), is("test.wikipedia.org")); } @Test public void testForLanguageCodeLanguage() { WikiSite subject = WikiSite.forLanguageCode("test"); assertThat(subject.languageCode(), is("test")); } @Test public void testForLanguageCodeNoLanguage() { WikiSite subject = WikiSite.forLanguageCode(""); assertThat(subject.languageCode(), is("")); } @Test public void testForLanguageCodeNoLanguageAuthority() { WikiSite subject = WikiSite.forLanguageCode(""); assertThat(subject.authority(), is("wikipedia.org")); } @Test public void testForLanguageCodeLanguageAuthority() { WikiSite subject = WikiSite.forLanguageCode("zh-hans"); assertThat(subject.authority(), is("zh.wikipedia.org")); assertThat(subject.languageCode(), is("zh-hans")); } @Test public void testCtorScheme() { WikiSite subject = new WikiSite("http://wikipedia.org"); assertThat(subject.scheme(), is("http")); } @Test public void testCtorDefaultScheme() { WikiSite subject = new WikiSite("wikipedia.org"); assertThat(subject.scheme(), is("https")); } @Test public void testCtorAuthority() { WikiSite subject = new WikiSite("test.wikipedia.org"); assertThat(subject.authority(), is("test.wikipedia.org")); } @Test public void testCtorAuthorityLanguage() { WikiSite subject = new WikiSite("test.wikipedia.org"); assertThat(subject.languageCode(), is("test")); } @Test public void testCtorAuthorityNoLanguage() { WikiSite subject = new WikiSite("wikipedia.org"); assertThat(subject.languageCode(), is("")); } @Test public void testCtordesktopAuthorityLanguage() { WikiSite subject = new WikiSite("test.m.wikipedia.org"); assertThat(subject.languageCode(), is("test")); } @Test public void testCtordesktopAuthorityNoLanguage() { WikiSite subject = new WikiSite("m.wikipedia.org"); assertThat(subject.languageCode(), is("")); } @Test public void testCtorUriLangVariant() { WikiSite subject = new WikiSite("zh.wikipedia.org/zh-hant/Foo"); assertThat(subject.authority(), is("zh.wikipedia.org")); assertThat(subject.subdomain(), is("zh")); assertThat(subject.languageCode(), is("zh-hant")); assertThat(subject.scheme(), is("https")); assertThat(subject.dbName(), is("zhwiki")); assertThat(subject.url(), is("https://zh.wikipedia.org")); } @Test public void testCtorUriLangVariantInSubdomain() { WikiSite subject = new WikiSite("zh-tw.wikipedia.org/wiki/Foo"); assertThat(subject.authority(), is("zh.wikipedia.org")); assertThat(subject.subdomain(), is("zh")); assertThat(subject.languageCode(), is("zh-tw")); assertThat(subject.scheme(), is("https")); assertThat(subject.dbName(), is("zhwiki")); assertThat(subject.url(), is("https://zh.wikipedia.org")); } @Test public void testCtorMobileUriLangVariant() { WikiSite subject = new WikiSite("zh.m.wikipedia.org/zh-hant/Foo"); assertThat(subject.authority(), is("zh.wikipedia.org")); assertThat(subject.subdomain(), is("zh")); assertThat(subject.languageCode(), is("zh-hant")); assertThat(subject.scheme(), is("https")); assertThat(subject.url(), is("https://zh.wikipedia.org")); } @Test public void testCtorUriNoLangVariant() { WikiSite subject = new WikiSite("http://zh.wikipedia.org/wiki/Foo"); assertThat(subject.authority(), is("zh.wikipedia.org")); assertThat(subject.subdomain(), is("zh")); assertThat(subject.languageCode(), is("zh-hant")); assertThat(subject.scheme(), is("http")); assertThat(subject.url(), is("http://zh.wikipedia.org")); } @Test public void testCtorUriGeneralLangVariant() { WikiSite subject = new WikiSite("http://zh.wikipedia.org/wiki/Foo"); assertThat(subject.authority(), is("zh.wikipedia.org")); assertThat(subject.subdomain(), is("zh")); assertThat(subject.languageCode(), is("zh-hant")); assertThat(subject.scheme(), is("http")); assertThat(subject.url(), is("http://zh.wikipedia.org")); } @Test public void testCtorParcel() throws Throwable { WikiSite subject = WikiSite.forLanguageCode("test"); TestParcelUtil.test(subject); } @Test public void testAuthority() { WikiSite subject = new WikiSite("test.wikipedia.org", "test"); assertThat(subject.authority(), is("test.wikipedia.org")); } @Test public void testDesktopAuthorityLanguage() { WikiSite subject = WikiSite.forLanguageCode("fiu-vro"); assertThat(subject.authority(), is("fiu-vro.wikipedia.org")); } @Test public void testDesktopAuthorityNoLanguage() { WikiSite subject = new WikiSite("wikipedia.org"); assertThat(subject.authority(), is("wikipedia.org")); } @Test public void testDesktopAuthorityLanguageAuthority() { WikiSite subject = new WikiSite("no.wikipedia.org", "nb"); assertThat(subject.authority(), is("no.wikipedia.org")); } @Test public void testDesktopAuthoritydesktopAuthority() { WikiSite subject = new WikiSite("ru.wikipedia.org"); assertThat(subject.authority(), is("ru.wikipedia.org")); } @Test public void testDbNameLanguage() { WikiSite subject = new WikiSite("en.wikipedia.org", "en"); assertThat(subject.dbName(), is("enwiki")); } @Test public void testDbNameSpecialLanguage() { WikiSite subject = new WikiSite("no.wikipedia.org", "nb"); assertThat(subject.dbName(), is("nowiki")); } @Test public void testDbNameWithOneUnderscore() { WikiSite subject = new WikiSite("zh-yue.wikipedia.org"); assertThat(subject.dbName(), is("zh_yuewiki")); } @Test public void testDbNameWithTwoUnderscore() { WikiSite subject = new WikiSite("zh-min-nan.wikipedia.org"); assertThat(subject.dbName(), is("zh_min_nanwiki")); } @Test public void testPath() { WikiSite subject = WikiSite.forLanguageCode("test"); assertThat(subject.path("Segment"), is("/w/Segment")); } @Test public void testPathEmpty() { WikiSite subject = WikiSite.forLanguageCode("test"); assertThat(subject.path(""), is("/w/")); } @Test public void testUrl() { WikiSite subject = new WikiSite("test.192.168.1.11:8080", "test"); assertThat(subject.url(), is("https://test.192.168.1.11:8080")); } @Test public void testUrlPath() { WikiSite subject = WikiSite.forLanguageCode("test"); assertThat(subject.url("Segment"), is("https://test.wikipedia.org/w/Segment")); } @Test public void testLanguageCode() { WikiSite subject = WikiSite.forLanguageCode("lang"); assertThat(subject.languageCode(), is("lang")); } @Test public void testUnmarshal() { WikiSite wiki = WikiSite.forLanguageCode("test"); assertThat(GsonUnmarshaller.unmarshal(WikiSite.class, GsonMarshaller.marshal(wiki)), is(wiki)); } @Test public void testUnmarshalScheme() { WikiSite wiki = new WikiSite("wikipedia.org", ""); assertThat(GsonUnmarshaller.unmarshal(WikiSite.class, GsonMarshaller.marshal(wiki)), is(wiki)); } @Test public void testTitleForInternalLink() { WikiSite wiki = WikiSite.forLanguageCode("en"); assertThat(new PageTitle("Main Page", wiki), is(wiki.titleForInternalLink(""))); assertThat(new PageTitle("Main Page", wiki), is(wiki.titleForInternalLink("/wiki/"))); assertThat(new PageTitle("wiki", wiki), is(wiki.titleForInternalLink("wiki"))); assertThat(new PageTitle("wiki", wiki), is(wiki.titleForInternalLink("/wiki/wiki"))); assertThat(new PageTitle("wiki/wiki", wiki), is(wiki.titleForInternalLink("/wiki/wiki/wiki"))); } @Test public void testEquals() { assertThat(WikiSite.forLanguageCode("en"), is(WikiSite.forLanguageCode("en"))); assertThat(WikiSite.forLanguageCode("ta"), not(WikiSite.forLanguageCode("en"))); assertThat(WikiSite.forLanguageCode("ta").equals("ta.wikipedia.org"), is(false)); } @Test public void testNormalization() { assertThat("bm.wikipedia.org", is(WikiSite.forLanguageCode("bm").authority())); } }
package io.tek256.game; import org.joml.Vector2f; import io.tek256.Util; import io.tek256.game.items.Potion; import io.tek256.game.items.TestArmor; import io.tek256.game.items.TestItem; import io.tek256.input.Keyboard; import io.tek256.net.Net; import io.tek256.render.TextureSheet; import io.tek256.render.gui.GUIElement.AnchorX; import io.tek256.render.gui.GUIElement.AnchorY; import io.tek256.runtime.Scene; import io.tek256.render.gui.GUIText; import io.tek256.render.Texture; public class Console { private Game parent; private GUIText consoleLabel,consoleLine; private GUIText[] consoleLines; private boolean allowConsole = false; private boolean canBackspace = false; private boolean backspaceRepeat = false; private boolean backspace = false; private float backspaceEnterRepeat = 0.3f; private float consoleTimer; private float consoleLifeTime = 2f; private float backspaceRate = 0.1f; private float backspaceLife = 0; public TextureSheet target; private int curTex = 0; private int lines = 5; private StringBuilder cl; public Console(Game parent){ this.parent = parent; consoleLabel = new GUIText(">"); consoleLabel.setAnchor(AnchorX.LEFT,AnchorY.BOTTOM); consoleLabel.setPadding(new Vector2f(40f,-40f)); consoleLine = new GUIText(""); consoleLine.setAnchor(AnchorX.LEFT, AnchorY.BOTTOM); consoleLine.setPadding(new Vector2f(75f,-40f)); cl = new StringBuilder(); setLineCount(lines); Scene.getCurrent().add(consoleLine,consoleLabel); Scene.getCurrent().add(consoleLines); } public void handle(String line){ if(line.startsWith("/")){ String cmd = line.substring(1); String val = ""; if(line.contains(" ")){ cmd = cmd.split(" ")[0]; if(line.substring(1).split(" ").length > 1) val = line.substring(line.indexOf(" ")+1).trim(); } switch(cmd){ case "out": if(target != null && !val.equals("")){ target.saveMappings(val); addConsoleLine("Saving mappings to:"+val); }else{ if(val.equals("")) addConsoleLine("No path to write target to"); else if(target == null) addConsoleLine("No target to write"); } break; case "n": if(target == null){ addConsoleLine("No target sheet selected"); }else{ target.name(val, curTex); curTex++; parent.tset.setTexture(target.getSubTexture(curTex)); } break; case "b": if(target != null){ curTex = (curTex > 0) ? curTex-1 : 0; parent.c.getMesh().getMaterial().setTexture(target.getSubTexture(curTex)); addConsoleLine("Current Texture:"+curTex); } break; case "gn": if(target != null){ if(val.equals("")){ addConsoleLine(curTex+": "+target.getName(curTex)); }else if(val.toLowerCase().equals("all")){ StringBuilder[] lines = new StringBuilder[consoleLines.length]; if(target.getNamedLength() < lines.length){ lines = new StringBuilder[target.getNamedLength()]; } for(int i=0;i<lines.length;i++) lines[i] = new StringBuilder(); String[] keyset = target.getNamedKeyset(); for(int i=0;i<keyset.length;i++){ int toline = (int)i % lines.length; int index = target.getNameIndex(keyset[i]); lines[toline].append(keyset[i]+":"+index+" "); } for(int i=0;i<lines.length;i++) addConsoleLine(lines[i].toString()); }else if(val.toLowerCase().equals("count")){ addConsoleLine("Listing count: "+target.getNamedLength()); } } break; case "t": if(!val.equals("")){ target = TextureSheet.getSheet(val); if(target != null) addConsoleLine("Target set to: "+val); else addConsoleLine("Target unable to be found"); } break; case "s": if(target != null){ if(!val.equals("")){ curTex = Util.getInt(val); addConsoleLine("Current Texture set to: "+curTex); Texture t = target.getSubTexture(curTex); parent.c.getMesh().getMaterial().setTexture(t); } }else addConsoleLine("Cannot change texture without target sheet"); break; case "cls": clearConsole(); break; case "fs": if(!val.equals("")){ parent.text.setFontSize(Util.getInt(val)); } break; case "gg": addConsoleLine(target.getTexture().getPath()); break; case "pos": addConsoleLine("Player position:"+Util.asString(Player.getPlayerPosition())); break; case "inv": if(val.equals("")){ //no params String[] lns = Player.getInstance().getInventory().getFormattedItemStrings(); StringBuilder oln = new StringBuilder(); //because I can't do math without food oln.append(lns[0]+" "+lns[1]); addConsoleLine(oln.toString()); oln.setLength(0); oln.append(lns[2]+" "+lns[3]); addConsoleLine(oln.toString()); oln.setLength(0); oln.append(lns[4]+" "+lns[5]); addConsoleLine(oln.toString()); oln.setLength(0); }else if(!val.equals("")){ //params if(val.equals("w")){ for(String ln : Player.getInstance().getInventory().getFormattedWearableStrings()) addConsoleLine(ln); }else{ int slot = Util.getInt(val); addConsoleLine(Player.getInstance().getInventory().getSlot(slot).getFormattedString()); } } break; case "eq": if(!val.equals("")){ if(val.equals("test")){ Player.getInstance().getInventory().equip(new TestArmor()); }else if(val.equals("sword")){ Player.getInstance().getInventory().add(new TestItem()); }else if(val.equals("potion")){ Player.getInstance().getInventory().add(new Potion()); } }else{ addConsoleLine(Player.getInstance().getInventory().getArmorStats().toString()); } break; case "rmw": if(!val.equals("")){ int rm = Util.getInt(val); Player.getInstance().getInventory().removeWearable(rm); addConsoleLine("Removed: "+rm+"."); } break; case "set_clf": if(!val.equals("")){ consoleLifeTime = Util.getFloat(val); addConsoleLine("Console fade lifetime set to: "+consoleLifeTime+" seconds"); } break; case "set_mcl": if(!val.equals("")){ int nl = Util.getInt(val); setLineCount(nl); addConsoleLine("Console lines set to: "+nl); } break; case "gen": if(!val.equals("")){ parent.dungeon.generate(); parent.dungeon.output(val); }else{ parent.dungeon.generate(); parent.dungeon.output("test.png"); } break; case "exit": parent.end(); break; case "ping": if(!val.equals("")){ addConsoleLine(val+" "+(Net.ping(val) ? "is" : "isn't") + " reachable."); } break; } } } public void setLineCount(int count){ GUIText[] tempLines = new GUIText[count]; if(consoleLines != null){ if(count > lines){ for(int i=0;i<count;i++){ if(i < lines){ tempLines[i] = consoleLines[i]; consoleLines[i] = null; }else{ tempLines[i] = new GUIText(""); tempLines[i].setAnchor(AnchorX.LEFT, AnchorY.BOTTOM); tempLines[i].setPadding(new Vector2f(75f,-65f-(i*25))); tempLines[i].setZ(0.1f); Scene.getCurrent().add(tempLines[i]); } } }else if(count < lines){ for(int i=0;i<count;i++){ tempLines[i] = consoleLines[i]; consoleLines[i] = null; } } Scene.getCurrent().remove(consoleLines); }else{ for(int i=0;i<count;i++){ tempLines[i] = new GUIText(""); tempLines[i].setAnchor(AnchorX.LEFT, AnchorY.BOTTOM); tempLines[i].setPadding(new Vector2f(75f,-65f-(i*25))); tempLines[i].setZ(0.1f); Scene.getCurrent().add(tempLines[i]); } } consoleLines = tempLines; lines = count; } private void addConsoleLine(String line){ for(int i=consoleLines.length-1;i>0;i--){ consoleLines[i].setText(consoleLines[i-1].getText()); } consoleLines[0].setText(line); } private void clearConsole(){ for(int i=0;i<consoleLines.length;i++) consoleLines[i].setText(""); } public void input(float delta){ if(Keyboard.isClicked(Keyboard.KEY_ENTER) && allowConsole && cl.length() > 0){ addConsoleLine(cl.toString()); handle(cl.toString()); cl.setLength(0); consoleLine.setText(""); } if(Keyboard.isClicked(Keyboard.KEY_ENTER)){ allowConsole = !allowConsole; setVisibility(allowConsole); } if(allowConsole && Keyboard.isClicked(Keyboard.KEY_BACKSPACE) && cl.length() > 0){ cl.setLength(cl.length()-1); consoleLine.setText(cl.toString()); backspaceLife = backspaceEnterRepeat; backspaceRepeat = true; canBackspace = false; } if(Keyboard.isPressed(Keyboard.KEY_BACKSPACE)) backspace = true; else backspace = false; if(allowConsole && canBackspace && backspace && backspaceRepeat && cl.length() > 0){ cl.setLength(cl.length()-1); consoleLine.setText(cl.toString()); canBackspace = false; backspaceRepeat = true; backspaceLife = backspaceRate; } if(Keyboard.hasNext() && allowConsole){ for(Character c : Keyboard.getNext()){ if(Keyboard.isClicked(c)) if(Keyboard.isPressed(Keyboard.KEY_LEFT_SHIFT) || Keyboard.isPressed(Keyboard.KEY_RIGHT_SHIFT)) cl.append(Keyboard.getAlt(c)); else cl.append(c); } consoleLine.setText(cl.toString()); } } public void update(float delta){ if(consoleTimer > 0) consoleTimer -= delta; if(consoleTimer <= 0 && !allowConsole){ for(int i=0;i<consoleLines.length;i++) consoleLines[i].setVisible(false); } if(backspaceLife > 0) backspaceLife -= delta; if(backspaceLife <= 0){ canBackspace = true; if(backspaceRepeat && !backspace) backspaceRepeat = false; } } private void setVisibility(boolean visibility){ if(visibility){ for(int i=0;i<consoleLines.length;i++) consoleLines[i].setVisible(true); } consoleLine.setVisible(visibility); consoleLabel.setVisible(visibility); if(!visibility) consoleTimer = consoleLifeTime; } public boolean isOpen(){ return allowConsole; } }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser.accessibility; import android.content.Context; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.SpannableString; import android.text.style.URLSpan; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.RenderCoordinates; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Native accessibility for a {@link ContentViewCore}. */ @JNINamespace("content") public class BrowserAccessibilityManager { private static final String TAG = "BrowserAccessibilityManager"; // Constants from AccessibilityNodeInfo defined in the L SDK. private static final int ACTION_SET_TEXT = 0x200000; private static final String ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE = "ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE"; private final AccessibilityNodeProvider mAccessibilityNodeProvider; private ContentViewCore mContentViewCore; private final AccessibilityManager mAccessibilityManager; private final RenderCoordinates mRenderCoordinates; private long mNativeObj; private Rect mAccessibilityFocusRect; private boolean mIsHovering; private int mLastHoverId = View.NO_ID; private int mCurrentRootId; private final int[] mTempLocation = new int[2]; private final ViewGroup mView; private boolean mUserHasTouchExplored; private boolean mPendingScrollToMakeNodeVisible; private boolean mNotifyFrameInfoInitializedCalled; private int mSelectionGranularity; private int mSelectionStartIndex; private int mSelectionEndIndex; protected int mAccessibilityFocusId; protected boolean mVisible = true; /** * Create a BrowserAccessibilityManager object, which is owned by the C++ * BrowserAccessibilityManagerAndroid instance, and connects to the content view. * @param nativeBrowserAccessibilityManagerAndroid A pointer to the counterpart native * C++ object that owns this object. * @param contentViewCore The content view that this object provides accessibility for. */ @CalledByNative private static BrowserAccessibilityManager create(long nativeBrowserAccessibilityManagerAndroid, ContentViewCore contentViewCore) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return new LollipopBrowserAccessibilityManager( nativeBrowserAccessibilityManagerAndroid, contentViewCore); } else { return new BrowserAccessibilityManager( nativeBrowserAccessibilityManagerAndroid, contentViewCore); } } protected BrowserAccessibilityManager(long nativeBrowserAccessibilityManagerAndroid, ContentViewCore contentViewCore) { mNativeObj = nativeBrowserAccessibilityManagerAndroid; mContentViewCore = contentViewCore; mAccessibilityFocusId = View.NO_ID; mIsHovering = false; mCurrentRootId = View.NO_ID; mView = mContentViewCore.getContainerView(); mRenderCoordinates = mContentViewCore.getRenderCoordinates(); mAccessibilityManager = (AccessibilityManager) mContentViewCore.getContext() .getSystemService(Context.ACCESSIBILITY_SERVICE); final BrowserAccessibilityManager delegate = this; mAccessibilityNodeProvider = new AccessibilityNodeProvider() { @Override public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { return delegate.createAccessibilityNodeInfo(virtualViewId); } @Override public List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String text, int virtualViewId) { return delegate.findAccessibilityNodeInfosByText(text, virtualViewId); } @Override public boolean performAction(int virtualViewId, int action, Bundle arguments) { return delegate.performAction(virtualViewId, action, arguments); } }; // This must occur last as it may cause a call to notifyFrameInfoInitialized. mContentViewCore.setBrowserAccessibilityManager(this); } @CalledByNative private void onNativeObjectDestroyed() { if (mContentViewCore.getBrowserAccessibilityManager() == this) { mContentViewCore.setBrowserAccessibilityManager(null); } mNativeObj = 0; mContentViewCore = null; } /** * @return An AccessibilityNodeProvider. */ public AccessibilityNodeProvider getAccessibilityNodeProvider() { return mAccessibilityNodeProvider; } /** * Set whether the web content made accessible by this class is currently visible. * Set it to false if the web view is still on the screen but it's obscured by a * dialog or overlay. This will make every virtual view in the web hierarchy report * that it's not visible, and not accessibility focusable. * * @param visible Whether the web content is currently visible and not obscured. */ public void setVisible(boolean visible) { if (visible == mVisible) return; mVisible = visible; mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } /** * @see AccessibilityNodeProvider#createAccessibilityNodeInfo(int) */ protected AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { if (!mAccessibilityManager.isEnabled() || mNativeObj == 0) { return null; } int rootId = nativeGetRootId(mNativeObj); if (virtualViewId == View.NO_ID) { return createNodeForHost(rootId); } if (!isFrameInfoInitialized()) { return null; } final AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(mView); info.setPackageName(mContentViewCore.getContext().getPackageName()); info.setSource(mView, virtualViewId); if (virtualViewId == rootId) { info.setParent(mView); } if (nativePopulateAccessibilityNodeInfo(mNativeObj, info, virtualViewId)) { return info; } else { info.recycle(); return null; } } /** * @see AccessibilityNodeProvider#findAccessibilityNodeInfosByText(String, int) */ protected List<AccessibilityNodeInfo> findAccessibilityNodeInfosByText(String text, int virtualViewId) { return new ArrayList<AccessibilityNodeInfo>(); } protected static boolean isValidMovementGranularity(int granularity) { switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: return true; } return false; } /** * @see AccessibilityNodeProvider#performAction(int, int, Bundle) */ protected boolean performAction(int virtualViewId, int action, Bundle arguments) { // We don't support any actions on the host view or nodes // that are not (any longer) in the tree. if (!mAccessibilityManager.isEnabled() || mNativeObj == 0 || !nativeIsNodeValid(mNativeObj, virtualViewId)) { return false; } switch (action) { case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: if (!moveAccessibilityFocusToId(virtualViewId)) return true; if (!mIsHovering) { nativeScrollToMakeNodeVisible( mNativeObj, mAccessibilityFocusId); } else { mPendingScrollToMakeNodeVisible = true; } return true; case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: // ALWAYS respond with TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED whether we thought // it had focus or not, so that the Android framework cache is correct. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); if (mAccessibilityFocusId == virtualViewId) { mAccessibilityFocusId = View.NO_ID; mAccessibilityFocusRect = null; } return true; case AccessibilityNodeInfo.ACTION_CLICK: nativeClick(mNativeObj, virtualViewId); sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_CLICKED); return true; case AccessibilityNodeInfo.ACTION_FOCUS: nativeFocus(mNativeObj, virtualViewId); return true; case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: nativeBlur(mNativeObj); return true; case AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT: { if (arguments == null) return false; String elementType = arguments.getString( AccessibilityNodeInfo.ACTION_ARGUMENT_HTML_ELEMENT_STRING); if (elementType == null) return false; elementType = elementType.toUpperCase(Locale.US); return jumpToElementType(elementType, true); } case AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT: { if (arguments == null) return false; String elementType = arguments.getString( AccessibilityNodeInfo.ACTION_ARGUMENT_HTML_ELEMENT_STRING); if (elementType == null) return false; elementType = elementType.toUpperCase(Locale.US); return jumpToElementType(elementType, false); } case ACTION_SET_TEXT: { if (!nativeIsEditableText(mNativeObj, virtualViewId)) return false; if (arguments == null) return false; String newText = arguments.getString( ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE); if (newText == null) return false; nativeSetTextFieldValue(mNativeObj, virtualViewId, newText); // Match Android framework and set the cursor to the end of the text field. nativeSetSelection(mNativeObj, virtualViewId, newText.length(), newText.length()); return true; } case AccessibilityNodeInfo.ACTION_SET_SELECTION: { if (!nativeIsEditableText(mNativeObj, virtualViewId)) return false; int selectionStart = 0; int selectionEnd = 0; if (arguments != null) { selectionStart = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT); selectionEnd = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT); } nativeSetSelection(mNativeObj, virtualViewId, selectionStart, selectionEnd); return true; } case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { if (arguments == null) return false; int granularity = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); boolean extend = arguments.getBoolean( AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); if (!isValidMovementGranularity(granularity)) { return false; } return nextAtGranularity(granularity, extend); } case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { if (arguments == null) return false; int granularity = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); boolean extend = arguments.getBoolean( AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); if (!isValidMovementGranularity(granularity)) { return false; } return previousAtGranularity(granularity, extend); } case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: return nativeAdjustSlider(mNativeObj, virtualViewId, true); case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: return nativeAdjustSlider(mNativeObj, virtualViewId, false); default: break; } return false; } /** * @see View#onHoverEvent(MotionEvent) */ public boolean onHoverEvent(MotionEvent event) { if (!mAccessibilityManager.isEnabled() || mNativeObj == 0) { return false; } if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) { mIsHovering = false; if (mPendingScrollToMakeNodeVisible) { nativeScrollToMakeNodeVisible( mNativeObj, mAccessibilityFocusId); } mPendingScrollToMakeNodeVisible = false; return true; } mIsHovering = true; mUserHasTouchExplored = true; float x = event.getX(); float y = event.getY(); // Convert to CSS coordinates. int cssX = (int) (mRenderCoordinates.fromPixToLocalCss(x)); int cssY = (int) (mRenderCoordinates.fromPixToLocalCss(y)); // This sends an IPC to the render process to do the hit testing. // The response is handled by handleHover. nativeHitTest(mNativeObj, cssX, cssY); return true; } /** * Called by ContentViewCore to notify us when the frame info is initialized, * the first time, since until that point, we can't use mRenderCoordinates to transform * web coordinates to screen coordinates. */ public void notifyFrameInfoInitialized() { if (mNotifyFrameInfoInitializedCalled) return; mNotifyFrameInfoInitializedCalled = true; // Invalidate the container view, since the chrome accessibility tree is now // ready and listed as the child of the container view. mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); // (Re-) focus focused element, since we weren't able to create an // AccessibilityNodeInfo for this element before. if (mAccessibilityFocusId != View.NO_ID) { moveAccessibilityFocusToIdAndRefocusIfNeeded(mAccessibilityFocusId); } } private boolean jumpToElementType(String elementType, boolean forwards) { int id = nativeFindElementType(mNativeObj, mAccessibilityFocusId, elementType, forwards); if (id == 0) return false; moveAccessibilityFocusToId(id); return true; } private void setGranularityAndUpdateSelection(int granularity) { if (mSelectionGranularity == 0) { mSelectionStartIndex = -1; mSelectionEndIndex = -1; } mSelectionGranularity = granularity; if (nativeIsEditableText(mNativeObj, mAccessibilityFocusId)) { mSelectionStartIndex = nativeGetEditableTextSelectionStart( mNativeObj, mAccessibilityFocusId); mSelectionEndIndex = nativeGetEditableTextSelectionEnd( mNativeObj, mAccessibilityFocusId); } } private boolean nextAtGranularity(int granularity, boolean extendSelection) { setGranularityAndUpdateSelection(granularity); // This calls finishGranularityMove when it's done. return nativeNextAtGranularity(mNativeObj, mSelectionGranularity, extendSelection, mAccessibilityFocusId, mSelectionEndIndex); } private boolean previousAtGranularity(int granularity, boolean extendSelection) { setGranularityAndUpdateSelection(granularity); // This calls finishGranularityMove when it's done. return nativePreviousAtGranularity(mNativeObj, mSelectionGranularity, extendSelection, mAccessibilityFocusId, mSelectionEndIndex); } @CalledByNative private void finishGranularityMove(String text, boolean extendSelection, int itemStartIndex, int itemEndIndex, boolean forwards) { // Prepare to send both a selection and a traversal event in sequence. AccessibilityEvent selectionEvent = buildAccessibilityEvent(mAccessibilityFocusId, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); if (selectionEvent == null) return; AccessibilityEvent traverseEvent = buildAccessibilityEvent(mAccessibilityFocusId, AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); if (traverseEvent == null) { selectionEvent.recycle(); return; } // Update the cursor or selection based on the traversal. If it's an editable // text node, set the real editing cursor too. if (forwards) { mSelectionEndIndex = itemEndIndex; } else { mSelectionEndIndex = itemStartIndex; } if (!extendSelection) { mSelectionStartIndex = mSelectionEndIndex; } if (nativeIsEditableText(mNativeObj, mAccessibilityFocusId)) { nativeSetSelection(mNativeObj, mAccessibilityFocusId, mSelectionStartIndex, mSelectionEndIndex); } // The selection event's "from" and "to" indices are just a cursor at the focus // end of the movement, or a selection if extendSelection is true. selectionEvent.setFromIndex(mSelectionStartIndex); selectionEvent.setToIndex(mSelectionStartIndex); selectionEvent.setItemCount(text.length()); // The traverse event's "from" and "to" indices surround the item (e.g. the word, // etc.) with no whitespace. traverseEvent.setFromIndex(itemStartIndex); traverseEvent.setToIndex(itemEndIndex); traverseEvent.setItemCount(text.length()); traverseEvent.setMovementGranularity(mSelectionGranularity); traverseEvent.setContentDescription(text); // The traverse event needs to set its associated action that triggered it. if (forwards) { traverseEvent.setAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); } else { traverseEvent.setAction( AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); } mView.requestSendAccessibilityEvent(mView, selectionEvent); mView.requestSendAccessibilityEvent(mView, traverseEvent); } private boolean moveAccessibilityFocusToId(int newAccessibilityFocusId) { if (newAccessibilityFocusId == mAccessibilityFocusId) return false; mAccessibilityFocusId = newAccessibilityFocusId; mAccessibilityFocusRect = null; mSelectionGranularity = 0; mSelectionStartIndex = 0; mSelectionEndIndex = 0; // Calling nativeSetAccessibilityFocus will asynchronously load inline text boxes for // this node and its subtree. If accessibility focus is on anything other than // the root, do it - otherwise set it to -1 so we don't load inline text boxes // for the whole subtree of the root. if (mAccessibilityFocusId == mCurrentRootId) { nativeSetAccessibilityFocus(mNativeObj, -1); } else { nativeSetAccessibilityFocus(mNativeObj, mAccessibilityFocusId); } sendAccessibilityEvent(mAccessibilityFocusId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); return true; } private void moveAccessibilityFocusToIdAndRefocusIfNeeded(int newAccessibilityFocusId) { // Work around a bug in the Android framework where it doesn't fully update the object // with accessibility focus even if you send it a WINDOW_CONTENT_CHANGED. To work around // this, clear focus and then set focus again. if (newAccessibilityFocusId == mAccessibilityFocusId) { sendAccessibilityEvent(newAccessibilityFocusId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mAccessibilityFocusId = View.NO_ID; } moveAccessibilityFocusToId(newAccessibilityFocusId); } private void sendAccessibilityEvent(int virtualViewId, int eventType) { // The container view is indicated by a virtualViewId of NO_ID; post these events directly // since there's no web-specific information to attach. if (virtualViewId == View.NO_ID) { mView.sendAccessibilityEvent(eventType); return; } AccessibilityEvent event = buildAccessibilityEvent(virtualViewId, eventType); if (event != null) { mView.requestSendAccessibilityEvent(mView, event); } } private AccessibilityEvent buildAccessibilityEvent(int virtualViewId, int eventType) { // If we don't have any frame info, then the virtual hierarchy // doesn't exist in the view of the Android framework, so should // never send any events. if (!mAccessibilityManager.isEnabled() || mNativeObj == 0 || !isFrameInfoInitialized()) { return null; } // This is currently needed if we want Android to visually highlight // the item that has accessibility focus. In practice, this doesn't seem to slow // things down, because it's only called when the accessibility focus moves. // TODO(dmazzoni): remove this if/when Android framework fixes bug. mView.postInvalidate(); final AccessibilityEvent event = AccessibilityEvent.obtain(eventType); event.setPackageName(mContentViewCore.getContext().getPackageName()); event.setSource(mView, virtualViewId); if (!nativePopulateAccessibilityEvent(mNativeObj, event, virtualViewId, eventType)) { event.recycle(); return null; } return event; } private Bundle getOrCreateBundleForAccessibilityEvent(AccessibilityEvent event) { Bundle bundle = (Bundle) event.getParcelableData(); if (bundle == null) { bundle = new Bundle(); event.setParcelableData(bundle); } return bundle; } private AccessibilityNodeInfo createNodeForHost(int rootId) { // Since we don't want the parent to be focusable, but we can't remove // actions from a node, copy over the necessary fields. final AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mView); final AccessibilityNodeInfo source = AccessibilityNodeInfo.obtain(mView); mView.onInitializeAccessibilityNodeInfo(source); // Copy over parent and screen bounds. Rect rect = new Rect(); source.getBoundsInParent(rect); result.setBoundsInParent(rect); source.getBoundsInScreen(rect); result.setBoundsInScreen(rect); // Set up the parent view, if applicable. final ViewParent parent = mView.getParentForAccessibility(); if (parent instanceof View) { result.setParent((View) parent); } // Populate the minimum required fields. result.setVisibleToUser(source.isVisibleToUser() && mVisible); result.setEnabled(source.isEnabled()); result.setPackageName(source.getPackageName()); result.setClassName(source.getClassName()); // Add the Chrome root node. if (isFrameInfoInitialized()) { result.addChild(mView, rootId); } return result; } /** * Returns whether or not the frame info is initialized, meaning we can safely * convert web coordinates to screen coordinates. When this is first initialized, * notifyFrameInfoInitialized is called - but we shouldn't check whether or not * that method was called as a way to determine if frame info is valid because * notifyFrameInfoInitialized might not be called at all if mRenderCoordinates * gets initialized first. */ private boolean isFrameInfoInitialized() { return mRenderCoordinates.getContentWidthCss() != 0.0 || mRenderCoordinates.getContentHeightCss() != 0.0; } @CalledByNative private void handlePageLoaded(int id) { if (mUserHasTouchExplored) return; if (mContentViewCore.shouldSetAccessibilityFocusOnPageLoad()) { moveAccessibilityFocusToIdAndRefocusIfNeeded(id); } } @CalledByNative private void handleFocusChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_FOCUSED); moveAccessibilityFocusToId(id); } @CalledByNative private void handleCheckStateChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_CLICKED); } @CalledByNative private void handleTextSelectionChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); } @CalledByNative private void handleEditableTextChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); } @CalledByNative private void handleSliderChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_SCROLLED); } @CalledByNative private void handleContentChanged(int id) { int rootId = nativeGetRootId(mNativeObj); if (rootId != mCurrentRootId) { mCurrentRootId = rootId; mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } else { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } } @CalledByNative private void handleNavigate() { mAccessibilityFocusId = View.NO_ID; mAccessibilityFocusRect = null; mUserHasTouchExplored = false; // Invalidate the host, since its child is now gone. mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } @CalledByNative private void handleScrollPositionChanged(int id) { sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_SCROLLED); } @CalledByNative private void handleScrolledToAnchor(int id) { moveAccessibilityFocusToId(id); } @CalledByNative private void handleHover(int id) { if (mLastHoverId == id) return; // Always send the ENTER and then the EXIT event, to match a standard Android View. sendAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); sendAccessibilityEvent(mLastHoverId, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); mLastHoverId = id; } @CalledByNative private void announceLiveRegionText(String text) { mView.announceForAccessibility(text); } @CalledByNative private void setAccessibilityNodeInfoParent(AccessibilityNodeInfo node, int parentId) { node.setParent(mView, parentId); } @CalledByNative private void addAccessibilityNodeInfoChild(AccessibilityNodeInfo node, int childId) { node.addChild(mView, childId); } @CalledByNative private void setAccessibilityNodeInfoBooleanAttributes(AccessibilityNodeInfo node, int virtualViewId, boolean checkable, boolean checked, boolean clickable, boolean enabled, boolean focusable, boolean focused, boolean password, boolean scrollable, boolean selected, boolean visibleToUser) { node.setCheckable(checkable); node.setChecked(checked); node.setClickable(clickable); node.setEnabled(enabled); node.setFocusable(focusable); node.setFocused(focused); node.setPassword(password); node.setScrollable(scrollable); node.setSelected(selected); node.setVisibleToUser(visibleToUser && mVisible); node.setMovementGranularities( AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE); if (mAccessibilityFocusId == virtualViewId) { node.setAccessibilityFocused(true); } else if (mVisible) { node.setAccessibilityFocused(false); } } // LollipopBrowserAccessibilityManager overrides this with the non-deprecated APIs. @SuppressWarnings("deprecation") @CalledByNative protected void addAccessibilityNodeInfoActions(AccessibilityNodeInfo node, int virtualViewId, boolean canScrollForward, boolean canScrollBackward, boolean clickable, boolean editableText, boolean enabled, boolean focusable, boolean focused) { node.addAction(AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT); node.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT); node.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); node.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); if (editableText && enabled) { node.addAction(ACTION_SET_TEXT); node.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (canScrollForward) { node.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (canScrollBackward) { node.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } if (focusable) { if (focused) { node.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); } else { node.addAction(AccessibilityNodeInfo.ACTION_FOCUS); } } if (mAccessibilityFocusId == virtualViewId) { node.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); } else if (mVisible) { node.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } if (clickable) { node.addAction(AccessibilityNodeInfo.ACTION_CLICK); } } @CalledByNative private void setAccessibilityNodeInfoClassName(AccessibilityNodeInfo node, String className) { node.setClassName(className); } @CalledByNative private void setAccessibilityNodeInfoContentDescription( AccessibilityNodeInfo node, String contentDescription, boolean annotateAsLink) { if (annotateAsLink) { SpannableString spannable = new SpannableString(contentDescription); spannable.setSpan(new URLSpan(""), 0, spannable.length(), 0); node.setContentDescription(spannable); } else { node.setContentDescription(contentDescription); } } @CalledByNative private void setAccessibilityNodeInfoLocation(AccessibilityNodeInfo node, final int virtualViewId, int absoluteLeft, int absoluteTop, int parentRelativeLeft, int parentRelativeTop, int width, int height, boolean isRootNode) { // First set the bounds in parent. Rect boundsInParent = new Rect(parentRelativeLeft, parentRelativeTop, parentRelativeLeft + width, parentRelativeTop + height); if (isRootNode) { // Offset of the web content relative to the View. boundsInParent.offset(0, (int) mRenderCoordinates.getContentOffsetYPix()); } node.setBoundsInParent(boundsInParent); // Now set the absolute rect, which requires several transformations. Rect rect = new Rect(absoluteLeft, absoluteTop, absoluteLeft + width, absoluteTop + height); // Offset by the scroll position. rect.offset(-(int) mRenderCoordinates.getScrollX(), -(int) mRenderCoordinates.getScrollY()); // Convert CSS (web) pixels to Android View pixels rect.left = (int) mRenderCoordinates.fromLocalCssToPix(rect.left); rect.top = (int) mRenderCoordinates.fromLocalCssToPix(rect.top); rect.bottom = (int) mRenderCoordinates.fromLocalCssToPix(rect.bottom); rect.right = (int) mRenderCoordinates.fromLocalCssToPix(rect.right); // Offset by the location of the web content within the view. rect.offset(0, (int) mRenderCoordinates.getContentOffsetYPix()); // Finally offset by the location of the view within the screen. final int[] viewLocation = new int[2]; mView.getLocationOnScreen(viewLocation); rect.offset(viewLocation[0], viewLocation[1]); node.setBoundsInScreen(rect); // Work around a bug in the Android framework where if the object with accessibility // focus moves, the accessibility focus rect is not updated - both the visual highlight, // and the location on the screen that's clicked if you double-tap. To work around this, // when we know the object with accessibility focus moved, move focus away and then // move focus right back to it, which tricks Android into updating its bounds. if (virtualViewId == mAccessibilityFocusId && virtualViewId != mCurrentRootId) { if (mAccessibilityFocusRect == null) { mAccessibilityFocusRect = rect; } else if (!mAccessibilityFocusRect.equals(rect)) { mAccessibilityFocusRect = rect; moveAccessibilityFocusToIdAndRefocusIfNeeded(virtualViewId); } } } @CalledByNative protected void setAccessibilityNodeInfoLollipopAttributes(AccessibilityNodeInfo node, boolean canOpenPopup, boolean contentInvalid, boolean dismissable, boolean multiLine, int inputType, int liveRegion) { // Requires Lollipop or higher. } @CalledByNative protected void setAccessibilityNodeInfoCollectionInfo(AccessibilityNodeInfo node, int rowCount, int columnCount, boolean hierarchical) { // Requires Lollipop or higher. } @CalledByNative protected void setAccessibilityNodeInfoCollectionItemInfo(AccessibilityNodeInfo node, int rowIndex, int rowSpan, int columnIndex, int columnSpan, boolean heading) { // Requires Lollipop or higher. } @CalledByNative protected void setAccessibilityNodeInfoRangeInfo(AccessibilityNodeInfo node, int rangeType, float min, float max, float current) { // Requires Lollipop or higher. } @CalledByNative private void setAccessibilityEventBooleanAttributes(AccessibilityEvent event, boolean checked, boolean enabled, boolean password, boolean scrollable) { event.setChecked(checked); event.setEnabled(enabled); event.setPassword(password); event.setScrollable(scrollable); } @CalledByNative private void setAccessibilityEventClassName(AccessibilityEvent event, String className) { event.setClassName(className); } @CalledByNative private void setAccessibilityEventListAttributes(AccessibilityEvent event, int currentItemIndex, int itemCount) { event.setCurrentItemIndex(currentItemIndex); event.setItemCount(itemCount); } @CalledByNative private void setAccessibilityEventScrollAttributes(AccessibilityEvent event, int scrollX, int scrollY, int maxScrollX, int maxScrollY) { event.setScrollX(scrollX); event.setScrollY(scrollY); event.setMaxScrollX(maxScrollX); event.setMaxScrollY(maxScrollY); } @CalledByNative private void setAccessibilityEventTextChangedAttrs(AccessibilityEvent event, int fromIndex, int addedCount, int removedCount, String beforeText, String text) { event.setFromIndex(fromIndex); event.setAddedCount(addedCount); event.setRemovedCount(removedCount); event.setBeforeText(beforeText); event.getText().add(text); } @CalledByNative private void setAccessibilityEventSelectionAttrs(AccessibilityEvent event, int fromIndex, int toIndex, int itemCount, String text) { event.setFromIndex(fromIndex); event.setToIndex(toIndex); event.setItemCount(itemCount); event.getText().add(text); } @CalledByNative protected void setAccessibilityEventLollipopAttributes(AccessibilityEvent event, boolean canOpenPopup, boolean contentInvalid, boolean dismissable, boolean multiLine, int inputType, int liveRegion) { // Backwards compatibility for Lollipop AccessibilityNodeInfo fields. Bundle bundle = getOrCreateBundleForAccessibilityEvent(event); bundle.putBoolean("AccessibilityNodeInfo.canOpenPopup", canOpenPopup); bundle.putBoolean("AccessibilityNodeInfo.contentInvalid", contentInvalid); bundle.putBoolean("AccessibilityNodeInfo.dismissable", dismissable); bundle.putBoolean("AccessibilityNodeInfo.multiLine", multiLine); bundle.putInt("AccessibilityNodeInfo.inputType", inputType); bundle.putInt("AccessibilityNodeInfo.liveRegion", liveRegion); } @CalledByNative protected void setAccessibilityEventCollectionInfo(AccessibilityEvent event, int rowCount, int columnCount, boolean hierarchical) { // Backwards compatibility for Lollipop AccessibilityNodeInfo fields. Bundle bundle = getOrCreateBundleForAccessibilityEvent(event); bundle.putInt("AccessibilityNodeInfo.CollectionInfo.rowCount", rowCount); bundle.putInt("AccessibilityNodeInfo.CollectionInfo.columnCount", columnCount); bundle.putBoolean("AccessibilityNodeInfo.CollectionInfo.hierarchical", hierarchical); } @CalledByNative protected void setAccessibilityEventHeadingFlag(AccessibilityEvent event, boolean heading) { // Backwards compatibility for Lollipop AccessibilityNodeInfo fields. Bundle bundle = getOrCreateBundleForAccessibilityEvent(event); bundle.putBoolean("AccessibilityNodeInfo.CollectionItemInfo.heading", heading); } @CalledByNative protected void setAccessibilityEventCollectionItemInfo(AccessibilityEvent event, int rowIndex, int rowSpan, int columnIndex, int columnSpan) { // Backwards compatibility for Lollipop AccessibilityNodeInfo fields. Bundle bundle = getOrCreateBundleForAccessibilityEvent(event); bundle.putInt("AccessibilityNodeInfo.CollectionItemInfo.rowIndex", rowIndex); bundle.putInt("AccessibilityNodeInfo.CollectionItemInfo.rowSpan", rowSpan); bundle.putInt("AccessibilityNodeInfo.CollectionItemInfo.columnIndex", columnIndex); bundle.putInt("AccessibilityNodeInfo.CollectionItemInfo.columnSpan", columnSpan); } @CalledByNative protected void setAccessibilityEventRangeInfo(AccessibilityEvent event, int rangeType, float min, float max, float current) { // Backwards compatibility for Lollipop AccessibilityNodeInfo fields. Bundle bundle = getOrCreateBundleForAccessibilityEvent(event); bundle.putInt("AccessibilityNodeInfo.RangeInfo.type", rangeType); bundle.putFloat("AccessibilityNodeInfo.RangeInfo.min", min); bundle.putFloat("AccessibilityNodeInfo.RangeInfo.max", max); bundle.putFloat("AccessibilityNodeInfo.RangeInfo.current", current); } @CalledByNative boolean shouldExposePasswordText() { return (Settings.Secure.getInt( mContentViewCore.getContext().getContentResolver(), Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0) == 1); } private native int nativeGetRootId(long nativeBrowserAccessibilityManagerAndroid); private native boolean nativeIsNodeValid(long nativeBrowserAccessibilityManagerAndroid, int id); private native boolean nativeIsEditableText( long nativeBrowserAccessibilityManagerAndroid, int id); private native int nativeGetEditableTextSelectionStart( long nativeBrowserAccessibilityManagerAndroid, int id); private native int nativeGetEditableTextSelectionEnd( long nativeBrowserAccessibilityManagerAndroid, int id); private native void nativeHitTest(long nativeBrowserAccessibilityManagerAndroid, int x, int y); private native boolean nativePopulateAccessibilityNodeInfo( long nativeBrowserAccessibilityManagerAndroid, AccessibilityNodeInfo info, int id); private native boolean nativePopulateAccessibilityEvent( long nativeBrowserAccessibilityManagerAndroid, AccessibilityEvent event, int id, int eventType); private native void nativeClick(long nativeBrowserAccessibilityManagerAndroid, int id); private native void nativeFocus(long nativeBrowserAccessibilityManagerAndroid, int id); private native void nativeBlur(long nativeBrowserAccessibilityManagerAndroid); private native void nativeScrollToMakeNodeVisible( long nativeBrowserAccessibilityManagerAndroid, int id); private native int nativeFindElementType(long nativeBrowserAccessibilityManagerAndroid, int startId, String elementType, boolean forwards); private native void nativeSetTextFieldValue(long nativeBrowserAccessibilityManagerAndroid, int id, String newValue); private native void nativeSetSelection(long nativeBrowserAccessibilityManagerAndroid, int id, int start, int end); private native boolean nativeNextAtGranularity(long nativeBrowserAccessibilityManagerAndroid, int selectionGranularity, boolean extendSelection, int id, int cursorIndex); private native boolean nativePreviousAtGranularity( long nativeBrowserAccessibilityManagerAndroid, int selectionGranularity, boolean extendSelection, int id, int cursorIndex); private native boolean nativeAdjustSlider( long nativeBrowserAccessibilityManagerAndroid, int id, boolean increment); private native void nativeSetAccessibilityFocus( long nativeBrowserAccessibilityManagerAndroid, int id); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.endpoint.dsl; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.stream.*; import javax.annotation.Generated; import org.apache.camel.builder.EndpointConsumerBuilder; import org.apache.camel.builder.EndpointProducerBuilder; import org.apache.camel.builder.endpoint.AbstractEndpointBuilder; /** * Perform operations on Kubernetes Service Accounts. * * Generated by camel build tools - do NOT edit this file! */ @Generated("org.apache.camel.maven.packaging.EndpointDslMojo") public interface KubernetesServiceAccountsEndpointBuilderFactory { /** * Builder for endpoint for the Kubernetes Service Account component. */ public interface KubernetesServiceAccountsEndpointBuilder extends EndpointProducerBuilder { default AdvancedKubernetesServiceAccountsEndpointBuilder advanced() { return (AdvancedKubernetesServiceAccountsEndpointBuilder) this; } /** * The Kubernetes API Version to use. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param apiVersion the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder apiVersion( String apiVersion) { doSetProperty("apiVersion", apiVersion); return this; } /** * The dns domain, used for ServiceCall EIP. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param dnsDomain the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder dnsDomain( String dnsDomain) { doSetProperty("dnsDomain", dnsDomain); return this; } /** * Default KubernetesClient to use if provided. * * The option is a: * &lt;code&gt;io.fabric8.kubernetes.client.KubernetesClient&lt;/code&gt; type. * * Group: producer * * @param kubernetesClient the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder kubernetesClient( io.fabric8.kubernetes.client.KubernetesClient kubernetesClient) { doSetProperty("kubernetesClient", kubernetesClient); return this; } /** * Default KubernetesClient to use if provided. * * The option will be converted to a * &lt;code&gt;io.fabric8.kubernetes.client.KubernetesClient&lt;/code&gt; type. * * Group: producer * * @param kubernetesClient the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder kubernetesClient( String kubernetesClient) { doSetProperty("kubernetesClient", kubernetesClient); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder lazyStartProducer( boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a &lt;code&gt;boolean&lt;/code&gt; * type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder lazyStartProducer( String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Producer operation to do on Kubernetes. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param operation the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder operation( String operation) { doSetProperty("operation", operation); return this; } /** * The port name, used for ServiceCall EIP. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param portName the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder portName( String portName) { doSetProperty("portName", portName); return this; } /** * The port protocol, used for ServiceCall EIP. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: tcp * Group: producer * * @param portProtocol the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder portProtocol( String portProtocol) { doSetProperty("portProtocol", portProtocol); return this; } /** * The CA Cert Data. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param caCertData the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder caCertData( String caCertData) { doSetProperty("caCertData", caCertData); return this; } /** * The CA Cert File. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param caCertFile the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder caCertFile( String caCertFile) { doSetProperty("caCertFile", caCertFile); return this; } /** * The Client Cert Data. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param clientCertData the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder clientCertData( String clientCertData) { doSetProperty("clientCertData", clientCertData); return this; } /** * The Client Cert File. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param clientCertFile the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder clientCertFile( String clientCertFile) { doSetProperty("clientCertFile", clientCertFile); return this; } /** * The Key Algorithm used by the client. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param clientKeyAlgo the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder clientKeyAlgo( String clientKeyAlgo) { doSetProperty("clientKeyAlgo", clientKeyAlgo); return this; } /** * The Client Key data. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param clientKeyData the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder clientKeyData( String clientKeyData) { doSetProperty("clientKeyData", clientKeyData); return this; } /** * The Client Key file. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param clientKeyFile the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder clientKeyFile( String clientKeyFile) { doSetProperty("clientKeyFile", clientKeyFile); return this; } /** * The Client Key Passphrase. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param clientKeyPassphrase the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder clientKeyPassphrase( String clientKeyPassphrase) { doSetProperty("clientKeyPassphrase", clientKeyPassphrase); return this; } /** * The Auth Token. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param oauthToken the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder oauthToken( String oauthToken) { doSetProperty("oauthToken", oauthToken); return this; } /** * Password to connect to Kubernetes. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param password the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder password( String password) { doSetProperty("password", password); return this; } /** * Define if the certs we used are trusted anyway or not. * * The option is a: &lt;code&gt;java.lang.Boolean&lt;/code&gt; type. * * Group: security * * @param trustCerts the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder trustCerts( Boolean trustCerts) { doSetProperty("trustCerts", trustCerts); return this; } /** * Define if the certs we used are trusted anyway or not. * * The option will be converted to a * &lt;code&gt;java.lang.Boolean&lt;/code&gt; type. * * Group: security * * @param trustCerts the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder trustCerts( String trustCerts) { doSetProperty("trustCerts", trustCerts); return this; } /** * Username to connect to Kubernetes. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param username the value to set * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder username( String username) { doSetProperty("username", username); return this; } } /** * Advanced builder for endpoint for the Kubernetes Service Account * component. */ public interface AdvancedKubernetesServiceAccountsEndpointBuilder extends EndpointProducerBuilder { default KubernetesServiceAccountsEndpointBuilder basic() { return (KubernetesServiceAccountsEndpointBuilder) this; } /** * Connection timeout in milliseconds to use when making requests to the * Kubernetes API server. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedKubernetesServiceAccountsEndpointBuilder connectionTimeout( Integer connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * Connection timeout in milliseconds to use when making requests to the * Kubernetes API server. * * The option will be converted to a * &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedKubernetesServiceAccountsEndpointBuilder connectionTimeout( String connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } } public interface KubernetesServiceAccountsBuilders { /** * Kubernetes Service Account (camel-kubernetes) * Perform operations on Kubernetes Service Accounts. * * Category: container,cloud,paas * Since: 2.17 * Maven coordinates: org.apache.camel:camel-kubernetes * * Syntax: <code>kubernetes-service-accounts:masterUrl</code> * * Path parameter: masterUrl (required) * Kubernetes Master url * * @param path masterUrl * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder kubernetesServiceAccounts( String path) { return KubernetesServiceAccountsEndpointBuilderFactory.endpointBuilder("kubernetes-service-accounts", path); } /** * Kubernetes Service Account (camel-kubernetes) * Perform operations on Kubernetes Service Accounts. * * Category: container,cloud,paas * Since: 2.17 * Maven coordinates: org.apache.camel:camel-kubernetes * * Syntax: <code>kubernetes-service-accounts:masterUrl</code> * * Path parameter: masterUrl (required) * Kubernetes Master url * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path masterUrl * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder kubernetesServiceAccounts( String componentName, String path) { return KubernetesServiceAccountsEndpointBuilderFactory.endpointBuilder(componentName, path); } } static KubernetesServiceAccountsEndpointBuilder endpointBuilder( String componentName, String path) { class KubernetesServiceAccountsEndpointBuilderImpl extends AbstractEndpointBuilder implements KubernetesServiceAccountsEndpointBuilder, AdvancedKubernetesServiceAccountsEndpointBuilder { public KubernetesServiceAccountsEndpointBuilderImpl(String path) { super(componentName, path); } } return new KubernetesServiceAccountsEndpointBuilderImpl(path); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.lens.cube.parse; import static java.util.Calendar.DAY_OF_MONTH; import static java.util.Calendar.HOUR_OF_DAY; import static org.apache.lens.cube.metadata.DateFactory.*; import static org.apache.lens.cube.metadata.UpdatePeriod.DAILY; import static org.apache.lens.cube.metadata.UpdatePeriod.HOURLY; import static org.apache.lens.cube.metadata.UpdatePeriod.MINUTELY; import static org.apache.lens.cube.metadata.UpdatePeriod.MONTHLY; import static org.apache.lens.cube.metadata.UpdatePeriod.QUARTERLY; import static org.apache.lens.cube.metadata.UpdatePeriod.YEARLY; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; import java.util.stream.Collectors; import javax.xml.bind.JAXBException; import org.apache.lens.api.ToXMLString; import org.apache.lens.api.jaxb.LensJAXBContext; import org.apache.lens.api.metastore.SchemaTraverser; import org.apache.lens.cube.metadata.*; import org.apache.lens.cube.metadata.timeline.EndsAndHolesPartitionTimeline; import org.apache.lens.cube.metadata.timeline.PartitionTimeline; import org.apache.lens.cube.metadata.timeline.StoreAllPartitionTimeline; import org.apache.lens.server.api.error.LensException; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrSubstitutor; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.ql.metadata.Hive; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.Table; import org.apache.hadoop.hive.ql.session.SessionState; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /* * Here is the cube test setup * * Cube : testCube * * Fact storage and Updates: * testFact : {C1, C2, C3, C4} -> {Minutely, hourly, daily, monthly, quarterly, yearly} * testFact2 : {C1} -> {Hourly} * testFactMonthly : {C2} -> {Monthly} * summary1,summary2,summary3 - {C1, C2} -> {daily, hourly, minutely} * cheapFact: {C99} -> {Minutely, hourly, daily, monthly, quarterly, yearly} * C2 has multiple dated partitions * C99 is not to be used as supported storage in testcases * * CityTable : C1 - SNAPSHOT and C2 - NO snapshot * * Cube : Basecube * Derived cubes : der1, der2,der3 * * Fact storage and Updates: * testFact1_BASE : {C1, C2, C3, C4} -> {Minutely, hourly, daily, monthly, quarterly, yearly} * testFact2_BASE : {C1, C2, C3, C4} -> {Minutely, hourly, daily, monthly, quarterly, yearly} * testFact1_RAW_BASE : {C1} -> {hourly} * testFact2_RAW_BASE : {C1} -> {hourly} */ @SuppressWarnings("deprecation") @Slf4j public class CubeTestSetup { private Set<CubeMeasure> cubeMeasures; private Set<CubeDimAttribute> cubeDimensions; public static final String TEST_CUBE_NAME = "testCube"; public static final String DERIVED_CUBE_NAME = "derivedCube"; public static final String BASE_CUBE_NAME = "baseCube"; public static final String VIRTUAL_CUBE_NAME = "virtualCube"; private static String c0 = "C0"; private static String c1 = "C1"; private static String c2 = "C2"; private static String c3 = "C3"; private static String c4 = "C4"; private static String c5 = "C5"; private static String c98 = "C98"; private static String c99 = "C99"; private static Map<String, String> factValidityProperties = Maps.newHashMap(); @Getter private static Map<String, List<UpdatePeriod>> storageToUpdatePeriodMap = new LinkedHashMap<>(); static { factValidityProperties.put(MetastoreConstants.FACT_RELATIVE_START_TIME, "now.year - 90 days"); } public static String getDateUptoHours(Date dt) { return HOURLY.format(dt); } interface StoragePartitionProvider { Map<String, String> providePartitionsForStorage(String storage); } public static String getExpectedUnionQuery(String cubeName, List<String> storages, StoragePartitionProvider provider, String outerSelectPart, String outerWhere, String outerPostWhere, String innerQuerySelectPart, String innerJoin, String innerWhere, String innerPostWhere) { if (!innerQuerySelectPart.trim().toLowerCase().endsWith("from")) { innerQuerySelectPart += " from "; } StringBuilder sb = new StringBuilder(); sb.append(outerSelectPart); if (!outerSelectPart.trim().toLowerCase().endsWith("from")) { sb.append(" from "); } sb.append(" ("); String sep = ""; for (String storage : storages) { sb.append(sep).append(getExpectedQuery(cubeName, innerQuerySelectPart + " ", innerJoin, innerWhere, innerPostWhere, null, provider.providePartitionsForStorage(storage))); sep = " UNION ALL "; } return sb.append(") ").append(" as ").append(cubeName).append(" ").append(outerWhere == null ? "" : outerWhere) .append(" ").append(outerPostWhere == null ? "" : outerPostWhere).toString(); } public static String getExpectedUnionQuery(String cubeName, List<String> storages, StoragePartitionProvider provider, String outerSelectPart, String outerWhere, String outerPostWhere, String innerQuerySelectPart, String innerWhere, String innerPostWhere) { return getExpectedUnionQuery(cubeName, storages, provider, outerSelectPart, outerWhere, outerPostWhere, innerQuerySelectPart, null, innerWhere, innerPostWhere); } public static String getExpectedQuery(String cubeName, String selExpr, String whereExpr, String postWhereExpr, Map<String, String> storageTableToWhereClause) { return getExpectedQuery(cubeName, selExpr, whereExpr, postWhereExpr, storageTableToWhereClause, null); } public static String getExpectedQuery(String cubeName, String selExpr, String whereExpr, String postWhereExpr, Map<String, String> storageTableToWhereClause, List<String> notLatestConditions) { StringBuilder expected = new StringBuilder(); for (Map.Entry<String, String> entry : storageTableToWhereClause.entrySet()) { String storageTable = entry.getKey(); expected.append(selExpr).append(storageTable).append(" ").append(cubeName).append(" WHERE ").append("("); if (notLatestConditions != null) { for (String cond : notLatestConditions) { expected.append(cond).append(" AND "); } } if (whereExpr != null) { expected.append(whereExpr).append(" AND "); } expected.append(entry.getValue()).append(")"); if (postWhereExpr != null) { expected.append(" ").append(postWhereExpr); } } return expected.toString(); } public static String getExpectedQuery(String cubeName, String selExpr, String whereExpr, String postWhereExpr, String rangeWhere, String storageTable) { return getExpectedQuery(cubeName, selExpr, whereExpr, postWhereExpr, rangeWhere, storageTable, null); } public static String getExpectedQuery(String cubeName, String selExpr, String whereExpr, String postWhereExpr, String rangeWhere, String storageTable, List<String> notLatestConditions) { StringBuilder expected = new StringBuilder() .append(selExpr).append(getDbName()).append(storageTable).append(" ").append(cubeName) .append(" WHERE ").append("("); if (notLatestConditions != null) { for (String cond : notLatestConditions) { expected.append(cond).append(" AND "); } } if (whereExpr != null) { expected.append(whereExpr).append(" AND "); } expected.append(rangeWhere).append(")"); if (postWhereExpr != null) { expected.append(postWhereExpr); } return expected.toString(); } public static String getExpectedQuery(String cubeName, String selExpr, String joinExpr, String whereExpr, String postWhereExpr, List<String> joinWhereConds, Map<String, String> storageTableToWhereClause) { return getExpectedQuery(cubeName, selExpr, joinExpr, whereExpr, postWhereExpr, joinWhereConds, storageTableToWhereClause, null); } public static String getExpectedQuery(String cubeName, String selExpr, String joinExpr, String whereExpr, String postWhereExpr, List<String> joinWhereConds, Map<String, String> storageTableToWhereClause, List<String> notLatestConditions) { StringBuilder expected = new StringBuilder(); int numTabs = storageTableToWhereClause.size(); assertEquals(1, numTabs); for (Map.Entry<String, String> entry : storageTableToWhereClause.entrySet()) { String storageTable = entry.getKey(); expected.append(selExpr).append(storageTable).append(" ").append(cubeName); if (joinExpr != null) { expected.append(joinExpr); } expected.append(" WHERE ").append("("); if (notLatestConditions != null) { for (String cond : notLatestConditions) { expected.append(cond).append(" AND "); } } if (whereExpr != null) { expected.append(whereExpr).append(" AND "); } expected.append(entry.getValue()); if (joinWhereConds != null) { for (String joinEntry : joinWhereConds) { expected.append(" AND ").append(joinEntry); } } expected.append(")"); if (postWhereExpr != null) { expected.append(postWhereExpr); } } return expected.toString(); } public static Map<String, String> getWhereForDailyAndHourly2days(String cubeName, String... storageTables) { return getWhereForDailyAndHourly2daysWithTimeDim(cubeName, "dt", storageTables); } public static String getDbName() { String database = SessionState.get().getCurrentDatabase(); if (!"default".equalsIgnoreCase(database) && StringUtils.isNotBlank(database)) { return database + "."; } return ""; } public static Map<String, String> getWhereForDailyAndHourly2daysWithTimeDim(String cubeName, String timedDimension, String... storageTables) { return getWhereForDailyAndHourly2daysWithTimeDim(cubeName, timedDimension, TWODAYS_BACK, NOW, storageTables); } public static Map<String, String> getWhereForDailyAndHourly2daysWithTimeDim(String cubeName, String timedDimension, Date from, Date to, String... storageTables) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<>(); if (storageToUpdatePeriodMap.isEmpty()) { String whereClause = getWhereForDailyAndHourly2daysWithTimeDim(cubeName, timedDimension, from, to); storageTableToWhereClause.put(getStorageTableString(storageTables), whereClause); } else { for (String tbl : storageTables) { for (UpdatePeriod updatePeriod : storageToUpdatePeriodMap.get(tbl)) { String whereClause = getWhereForDailyAndHourly2daysWithTimeDimUnionQuery(cubeName, timedDimension, from, to) .get(updatePeriod.getName()); storageTableToWhereClause.put(getStorageTableString(tbl), whereClause); } } } return storageTableToWhereClause; } private static String getStorageTableString(String... storageTables) { String dbName = getDbName(); if (!StringUtils.isBlank(dbName)) { List<String> tbls = new ArrayList<>(); for (String tbl : storageTables) { tbls.add(dbName + tbl); } return StringUtils.join(tbls, ","); } return StringUtils.join(storageTables, ","); } public static String getWhereForDailyAndHourly2daysWithTimeDim(String cubeName, String timedDimension, Date from, Date to) { Set<String> hourlyparts = new HashSet<>(); Set<String> dailyparts = new HashSet<>(); Date dayStart; if (!isZerothHour()) { addParts(hourlyparts, HOURLY, from, DateUtil.getCeilDate(from, DAILY)); addParts(hourlyparts, HOURLY, DateUtil.getFloorDate(to, DAILY), DateUtil.getFloorDate(to, HOURLY)); dayStart = DateUtil.getCeilDate(from, DAILY); } else { dayStart = from; } addParts(dailyparts, DAILY, dayStart, DateUtil.getFloorDate(to, DAILY)); List<String> parts = new ArrayList<>(); parts.addAll(hourlyparts); parts.addAll(dailyparts); Collections.sort(parts); return StorageUtil.getWherePartClause(timedDimension, cubeName, parts); } public static Map<String, String> getWhereForDailyAndHourly2daysWithTimeDimUnionQuery(String cubeName, String timedDimension, Date from, Date to) { Map<String, String> updatePeriodToWhereMap = new HashMap<String, String>(); List<String> hourlyparts = new ArrayList<String>(); List<String> dailyparts = new ArrayList<String>(); Date dayStart; if (!isZerothHour()) { addParts(hourlyparts, HOURLY, from, DateUtil.getCeilDate(from, DAILY)); addParts(hourlyparts, HOURLY, DateUtil.getFloorDate(to, DAILY), DateUtil.getFloorDate(to, HOURLY)); dayStart = DateUtil.getCeilDate(from, DAILY); } else { dayStart = from; } addParts(dailyparts, DAILY, dayStart, DateUtil.getFloorDate(to, DAILY)); updatePeriodToWhereMap.put("DAILY", StorageUtil.getWherePartClause(timedDimension, cubeName, dailyparts)); updatePeriodToWhereMap.put("HOURLY", StorageUtil.getWherePartClause(timedDimension, cubeName, hourlyparts)); return updatePeriodToWhereMap; } // storageName[0] is hourly // storageName[1] is daily // storageName[2] is monthly public static Map<String, String> getWhereForMonthlyDailyAndHourly2months(String cubeName, String... storageTables) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<String, String>(); List<String> hourlyparts = new ArrayList<String>(); List<String> dailyparts = new ArrayList<String>(); List<String> monthlyparts = new ArrayList<String>(); Date dayStart = TWO_MONTHS_BACK; Date monthStart = TWO_MONTHS_BACK; if (!isZerothHour()) { addParts(hourlyparts, HOURLY, TWO_MONTHS_BACK, DateUtil.getCeilDate(TWO_MONTHS_BACK, DAILY)); addParts(hourlyparts, HOURLY, DateUtil.getFloorDate(NOW, DAILY), DateUtil.getFloorDate(NOW, HOURLY)); dayStart = DateUtil.getCeilDate(TWO_MONTHS_BACK, DAILY); monthStart = DateUtil.getCeilDate(TWO_MONTHS_BACK, MONTHLY); } Calendar cal = new GregorianCalendar(); cal.setTime(dayStart); if (cal.get(DAY_OF_MONTH) != 1) { addParts(dailyparts, DAILY, dayStart, DateUtil.getCeilDate(TWO_MONTHS_BACK, MONTHLY)); monthStart = DateUtil.getCeilDate(TWO_MONTHS_BACK, MONTHLY); } addParts(dailyparts, DAILY, DateUtil.getFloorDate(NOW, MONTHLY), DateUtil.getFloorDate(NOW, DAILY)); addParts(monthlyparts, MONTHLY, monthStart, DateUtil.getFloorDate(NOW, MONTHLY)); List<String> parts = new ArrayList<String>(); parts.addAll(dailyparts); parts.addAll(hourlyparts); parts.addAll(monthlyparts); StringBuilder tables = new StringBuilder(); if (storageTables.length > 1) { if (!hourlyparts.isEmpty()) { tables.append(getDbName()); tables.append(storageTables[0]); tables.append(","); } tables.append(getDbName()); tables.append(storageTables[2]); if (!dailyparts.isEmpty()) { tables.append(","); tables.append(getDbName()); tables.append(storageTables[1]); } } else { tables.append(getDbName()); tables.append(storageTables[0]); } Collections.sort(parts); storageTableToWhereClause.put(tables.toString(), StorageUtil.getWherePartClause("dt", cubeName, parts)); return storageTableToWhereClause; } public static Map<String, String> getWhereForMonthlyDailyAndHourly2monthsUnionQuery(String storageTable) { Map<String, List<String>> updatePeriodToPart = new LinkedHashMap<String, List<String>>(); List<String> hourlyparts = new ArrayList<String>(); List<String> dailyparts = new ArrayList<String>(); List<String> monthlyparts = new ArrayList<String>(); Date dayStart = TWO_MONTHS_BACK; Date monthStart = TWO_MONTHS_BACK; if (!isZerothHour()) { addParts(hourlyparts, HOURLY, TWO_MONTHS_BACK, DateUtil.getCeilDate(TWO_MONTHS_BACK, DAILY)); addParts(hourlyparts, HOURLY, DateUtil.getFloorDate(NOW, DAILY), DateUtil.getFloorDate(NOW, HOURLY)); dayStart = DateUtil.getCeilDate(TWO_MONTHS_BACK, DAILY); monthStart = DateUtil.getCeilDate(TWO_MONTHS_BACK, MONTHLY); } Calendar cal = new GregorianCalendar(); cal.setTime(dayStart); if (cal.get(DAY_OF_MONTH) != 1) { addParts(dailyparts, DAILY, dayStart, DateUtil.getCeilDate(TWO_MONTHS_BACK, MONTHLY)); monthStart = DateUtil.getCeilDate(TWO_MONTHS_BACK, MONTHLY); } addParts(dailyparts, DAILY, DateUtil.getFloorDate(NOW, MONTHLY), DateUtil.getFloorDate(NOW, DAILY)); addParts(monthlyparts, MONTHLY, monthStart, DateUtil.getFloorDate(NOW, MONTHLY)); updatePeriodToPart.put("HOURLY", hourlyparts); updatePeriodToPart.put("DAILY", dailyparts); updatePeriodToPart.put("MONTHLY", monthlyparts); List<String> unionParts = new ArrayList<String>(); for (Map.Entry<String, List<UpdatePeriod>> entry : storageToUpdatePeriodMap.entrySet()) { String table = entry.getKey(); for (UpdatePeriod updatePeriod : entry.getValue()) { String uperiod = updatePeriod.getName(); if (table.equals(storageTable) && updatePeriodToPart.containsKey(uperiod)) { unionParts.addAll(updatePeriodToPart.get(uperiod)); Collections.sort(unionParts); } } } HashMap<String, String> tabWhere = new LinkedHashMap<String, String>(); tabWhere.put(getStorageTableString(storageTable), StorageUtil.getWherePartClause("dt", TEST_CUBE_NAME, unionParts)); return tabWhere; } public static Map<String, String> getWhereForMonthly2months(String monthlyTable) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<String, String>(); List<String> parts = new ArrayList<String>(); addParts(parts, MONTHLY, TWO_MONTHS_BACK, DateUtil.getFloorDate(NOW, MONTHLY)); storageTableToWhereClause.put(getDbName() + monthlyTable, StorageUtil.getWherePartClause("dt", TEST_CUBE_NAME, parts)); return storageTableToWhereClause; } public static Map<String, String> getWhereForDays(String dailyTable, Date startDay, Date endDay) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<>(); List<String> parts = new ArrayList<>(); addParts(parts, DAILY, startDay, DateUtil.getFloorDate(endDay, DAILY)); storageTableToWhereClause.put(getDbName() + dailyTable, StorageUtil.getWherePartClause("dt", TEST_CUBE_NAME, parts)); return storageTableToWhereClause; } public static Map<String, String> getWhereForUpdatePeriods(String cubeName, String table, Date start, Date end, Set<UpdatePeriod> updatePeriods) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<>(); List<String> parts = new ArrayList<>(); addParts(parts, updatePeriods, start, end); storageTableToWhereClause.put(getDbName() + table, StorageUtil.getWherePartClause("dt", cubeName, parts)); return storageTableToWhereClause; } public static Map<String, String> getWhereForMonthly(String monthlyTable, Date startMonth, Date endMonth) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<String, String>(); List<String> parts = new ArrayList<String>(); addParts(parts, MONTHLY, startMonth, endMonth); storageTableToWhereClause.put(getDbName() + monthlyTable, StorageUtil.getWherePartClause("dt", TEST_CUBE_NAME, parts)); return storageTableToWhereClause; } public static Map<String, String> getWhereForHourly2days(String hourlyTable) { return getWhereForHourly2days(TEST_CUBE_NAME, hourlyTable); } public static Map<String, String> getWhereForHourly2days(String alias, String hourlyTable) { Map<String, String> storageTableToWhereClause = new LinkedHashMap<String, String>(); List<String> parts = new ArrayList<String>(); addParts(parts, HOURLY, TWODAYS_BACK, DateUtil.getFloorDate(NOW, HOURLY)); storageTableToWhereClause.put(getDbName() + hourlyTable, StorageUtil.getWherePartClause("dt", alias, parts)); return storageTableToWhereClause; } public static void addParts(Collection<String> partitions, UpdatePeriod updatePeriod, Date from, Date to) { try { for (TimePartition timePartition : TimePartitionRange.between(from, to, updatePeriod)) { partitions.add(timePartition.toString()); } } catch (LensException e) { throw new IllegalArgumentException(e); } } public static void addParts(Collection<String> partitions, Set<UpdatePeriod> updatePeriods, Date from, Date to) { if (updatePeriods.size() != 0) { UpdatePeriod max = CubeFactTable.maxIntervalInRange(from, to, updatePeriods); if (max != null) { updatePeriods.remove(max); Date ceilFromDate = DateUtil.getCeilDate(from, max); Date floorToDate = DateUtil.getFloorDate(to, max); addParts(partitions, updatePeriods, from, ceilFromDate); addParts(partitions, max, ceilFromDate, floorToDate); addParts(partitions, updatePeriods, floorToDate, to); } } } public static String getExpectedQuery(String dimName, String selExpr, String postWhereExpr, String storageTable, boolean hasPart) { return getExpectedQuery(dimName, selExpr, null, null, postWhereExpr, storageTable, hasPart); } public static String getExpectedQuery(String dimName, String selExpr, String joinExpr, String whereExpr, String postWhereExpr, String storageTable, boolean hasPart) { StringBuilder expected = new StringBuilder(); String partWhere = null; if (hasPart) { partWhere = StorageUtil.getWherePartClause("dt", dimName, StorageConstants.getPartitionsForLatest()); } expected.append(selExpr); expected.append(getDbName() + storageTable); expected.append(" "); expected.append(dimName); if (joinExpr != null) { expected.append(joinExpr); } if (whereExpr != null || hasPart) { expected.append(" WHERE "); expected.append("("); if (whereExpr != null) { expected.append(whereExpr); if (partWhere != null) { expected.append(" AND "); } } if (partWhere != null) { expected.append(partWhere); } expected.append(")"); } if (postWhereExpr != null) { expected.append(postWhereExpr); } return expected.toString(); } private void assertTestFactTimelineClass(CubeMetastoreClient client) throws Exception { String factName = "testFact"; client.getTimelines(factName, c1, null, null); client.getTimelines(factName, c4, null, null); client.clearHiveTableCache(); CubeFactTable fact = client.getCubeFactTable(factName); Table table = client.getTable(MetastoreUtil.getStorageTableName(fact.getName(), Storage.getPrefix(c1))); assertEquals(table.getParameters().get(MetastoreUtil.getPartitionTimelineCachePresenceKey()), "true"); for (UpdatePeriod period : Lists.newArrayList(MINUTELY, HOURLY, DAILY, MONTHLY, YEARLY, QUARTERLY)) { for (String partCol : Lists.newArrayList("dt")) { assertTimeline(client, fact.getName(), c1, period, partCol, EndsAndHolesPartitionTimeline.class); } } table = client.getTable(MetastoreUtil.getStorageTableName(fact.getName(), Storage.getPrefix(c4))); assertEquals(table.getParameters().get(MetastoreUtil.getPartitionTimelineCachePresenceKey()), "true"); for (UpdatePeriod period : Lists.newArrayList(MINUTELY, HOURLY, DAILY, MONTHLY, YEARLY, QUARTERLY)) { for (String partCol : Lists.newArrayList("ttd", "ttd2")) { assertTimeline(client, fact.getName(), c4, period, partCol, EndsAndHolesPartitionTimeline.class); } } } private void assertTimeline(CubeMetastoreClient client, String factName, String storageName, UpdatePeriod updatePeriod, String timeDim, PartitionTimeline expectedTimeline) throws Exception { assertNotNull(factName); assertNotNull(storageName); assertNotNull(updatePeriod); assertNotNull(timeDim); String storageTableName = MetastoreUtil.getFactOrDimtableStorageTableName(factName, storageName); List<PartitionTimeline> timelines = client.getTimelines(factName, storageName, updatePeriod.name(), timeDim); assertEquals(timelines.size(), 1); PartitionTimeline actualTimeline = timelines.get(0); assertEquals(actualTimeline, expectedTimeline); assertEquals(client.getTable(storageTableName).getParameters() .get(MetastoreUtil.getPartitionTimelineStorageClassKey(updatePeriod, timeDim)), expectedTimeline.getClass().getCanonicalName()); expectedTimeline.init(client.getTable(MetastoreUtil.getFactOrDimtableStorageTableName(factName, storageName))); assertEquals(actualTimeline, expectedTimeline); } private void assertTimeline(CubeMetastoreClient client, String factName, String storageName, UpdatePeriod updatePeriod, String timeDim, Class<? extends PartitionTimeline> partitionTimelineClass) throws Exception { String storageTableName = MetastoreUtil.getFactOrDimtableStorageTableName(factName, storageName); PartitionTimeline expectedTimeline = partitionTimelineClass.getConstructor( String.class, UpdatePeriod.class, String.class) .newInstance(storageTableName, updatePeriod, timeDim); assertTimeline(client, factName, storageName, updatePeriod, timeDim, expectedTimeline); } private void createCubeCheapFactPartitions(CubeMetastoreClient client) throws HiveException, LensException { String factName = "cheapFact"; CubeFactTable fact = client.getCubeFactTable(factName); // Add all hourly partitions for two days Calendar cal = Calendar.getInstance(); cal.setTime(TWODAYS_BACK); Date temp = cal.getTime(); while (!(temp.after(NOW))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put("ttd", temp); timeParts.put("ttd2", temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, c99, CubeTableType.FACT); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } // Add all hourly partitions for TWO_DAYS_RANGE_BEFORE_4_DAYS cal.setTime(BEFORE_6_DAYS); temp = cal.getTime(); while (!(temp.after(BEFORE_4_DAYS))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put("ttd", temp); timeParts.put("ttd2", temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, c99, CubeTableType.FACT); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } } private void createTestFact2Partitions(CubeMetastoreClient client) throws Exception { String factName = "testFact2"; CubeFactTable fact = client.getCubeFactTable(factName); // Add all hourly partitions for two days Calendar cal = Calendar.getInstance(); cal.setTime(TWODAYS_BACK); Date temp = cal.getTime(); while (!(temp.after(NOW))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put(TestCubeMetastoreClient.getDatePartitionKey(), temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); try { client.addPartition(sPartSpec, c1, CubeTableType.FACT); } catch (HiveException e) { log.error("Encountered Hive exception.", e); } catch (LensException e) { log.error("Encountered Lens exception.", e); } cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } // Add all hourly partitions for TWO_DAYS_RANGE_BEFORE_4_DAYS cal.setTime(BEFORE_6_DAYS); temp = cal.getTime(); while (!(temp.after(BEFORE_4_DAYS))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put(TestCubeMetastoreClient.getDatePartitionKey(), temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, c1, CubeTableType.FACT); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } client.clearHiveTableCache(); Table table = client.getTable(MetastoreUtil.getStorageTableName(fact.getName(), Storage.getPrefix(c4))); table.getParameters().put(MetastoreUtil.getPartitionTimelineStorageClassKey(HOURLY, "ttd"), StoreAllPartitionTimeline.class.getCanonicalName()); table.getParameters().put(MetastoreUtil.getPartitionTimelineStorageClassKey(HOURLY, "ttd2"), StoreAllPartitionTimeline.class.getCanonicalName()); client.pushHiveTable(table); // Add all hourly partitions for two days on C4 cal = Calendar.getInstance(); cal.setTime(TWODAYS_BACK); temp = cal.getTime(); List<StoragePartitionDesc> storagePartitionDescs = Lists.newArrayList(); List<String> partitions = Lists.newArrayList(); StoreAllPartitionTimeline ttdStoreAll = new StoreAllPartitionTimeline(MetastoreUtil.getFactOrDimtableStorageTableName(fact.getName(), c4), HOURLY, "ttd"); StoreAllPartitionTimeline ttd2StoreAll = new StoreAllPartitionTimeline(MetastoreUtil.getFactOrDimtableStorageTableName(fact.getName(), c4), HOURLY, "ttd2"); while (!(temp.after(NOW))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put("ttd", temp); timeParts.put("ttd2", temp); TimePartition tp = TimePartition.of(HOURLY, temp); ttdStoreAll.add(tp); ttd2StoreAll.add(tp); partitions.add(HOURLY.format(temp)); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); storagePartitionDescs.add(sPartSpec); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } client.addPartitions(storagePartitionDescs, c4, CubeTableType.FACT); client.clearHiveTableCache(); table = client.getTable(MetastoreUtil.getStorageTableName(fact.getName(), Storage.getPrefix(c4))); assertEquals(table.getParameters().get(MetastoreUtil.getPartitionTimelineCachePresenceKey()), "true"); assertTimeline(client, fact.getName(), c4, HOURLY, "ttd", ttdStoreAll); assertTimeline(client, fact.getName(), c4, HOURLY, "ttd2", ttd2StoreAll); // Add all hourly partitions for TWO_DAYS_RANGE_BEFORE_4_DAYS cal.setTime(BEFORE_6_DAYS); temp = cal.getTime(); while (!(temp.after(BEFORE_4_DAYS))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put("ttd", temp); timeParts.put("ttd2", temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, c4, CubeTableType.FACT); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } } private void createTestFact2RawPartitions(CubeMetastoreClient client) throws HiveException, LensException { String factName = "testFact2_raw"; CubeFactTable fact2 = client.getCubeFactTable(factName); // Add all hourly partitions for two days Calendar cal = Calendar.getInstance(); cal.setTime(TWODAYS_BACK); Date temp = cal.getTime(); while (!(temp.after(NOW))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put(TestCubeMetastoreClient.getDatePartitionKey(), temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact2.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, c3, CubeTableType.FACT); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } } public void createSources(HiveConf conf, String dbName) throws Exception { try { Database database = new Database(); database.setName(dbName); Hive.get(conf).dropDatabase(dbName, true, true, true); Hive.get(conf).createDatabase(database); SessionState.get().setCurrentDatabase(dbName); CubeMetastoreClient client = CubeMetastoreClient.getInstance(conf); createFromXML(client); assertTestFactTimelineClass(client); createCubeCheapFactPartitions(client); // commenting this as the week date format throws IllegalPatternException // createCubeFactWeekly(client); createTestFact2Partitions(client); createTestFact2RawPartitions(client); createBaseCubeFactPartitions(client); createSummaryPartitions(client); // dump(client); } catch (Exception exc) { log.error("Exception while creating sources.", exc); throw exc; } } private static final StrSubstitutor GREGORIAN_SUBSTITUTOR = new StrSubstitutor(new StrLookup<String>() { @Override public String lookup(String s) { try { return JAXBUtils.getXMLGregorianCalendar(DateUtil.resolveDate(s, NOW)).toString(); } catch (LensException e) { throw new RuntimeException(e); } } }, "$gregorian{", "}", '$'); private static final StrSubstitutor ABSOLUTE_SUBSTITUTOR = new StrSubstitutor(new StrLookup<String>() { @Override public String lookup(String s) { try { return DateUtil.relativeToAbsolute(s, NOW); } catch (LensException e) { throw new RuntimeException(e); } } }, "$absolute{", "}", '$'); private void createFromXML(CubeMetastoreClient client) { SchemaTraverser.SchemaEntityProcessor processor = (file, aClass) -> { Function<String, String> f = GREGORIAN_SUBSTITUTOR::replace; Function<String, String> g = ABSOLUTE_SUBSTITUTOR::replace; try { BufferedReader br = new BufferedReader(new FileReader(file)); String replaced = br.lines().map(f.andThen(g)).collect(Collectors.joining("\n")); StringReader sr = new StringReader(replaced); client.createEntity(LensJAXBContext.unmarshall(sr)); } catch (LensException | JAXBException | IOException e) { throw new RuntimeException(e); } }; new SchemaTraverser(new File(getClass().getResource("/schema").getFile()), processor, null, null).run(); } private void dump(CubeMetastoreClient client) throws LensException, IOException { // for (CubeInterface cubeInterface : client.getAllCubes()) { // String path = getClass().getResource("/schema/cubes/" + ((cubeInterface instanceof Cube) ? "base" // : "derived")).getPath() + "/" + cubeInterface.getName() + ".xml"; // try(BufferedWriter bw = new BufferedWriter(new FileWriter(path))) { // bw.write(ToXMLString.toString(JAXBUtils.xCubeFromHiveCube(cubeInterface))); // } // } for (FactTable factTable : client.getAllFacts(false)) { CubeFactTable cubeFactTable = (CubeFactTable) factTable; try(BufferedWriter bw = new BufferedWriter(new FileWriter(getClass() .getResource("/schema/facts").getPath()+"/"+cubeFactTable.getName()+".xml"))) { bw.write(ToXMLString.toString(client.getXFactTable(cubeFactTable))); } } // for (Dimension dim : client.getAllDimensions()) { // try(BufferedWriter bw = new BufferedWriter(new FileWriter(getClass() // .getResource("/schema/dimensions").getPath()+"/"+dim.getName()+".xml"))) { // bw.write(ToXMLString.toString(JAXBUtils.xdimensionFromDimension(dim))); // } // } for (CubeDimensionTable dim : client.getAllDimensionTables()) { try(BufferedWriter bw = new BufferedWriter(new FileWriter(getClass() .getResource("/schema/dimtables").getPath()+"/"+dim.getName()+".xml"))) { bw.write(ToXMLString.toString(client.getXDimensionTable(dim))); } } // for (Storage storage : client.getAllStorages()) { // try(BufferedWriter bw = new BufferedWriter(new FileWriter(getClass() // .getResource("/schema/storages").getPath()+"/"+storage.getName()+".xml"))) { // bw.write(ToXMLString.toString(JAXBUtils.xstorageFromStorage(storage))); // } // } } public void dropSources(HiveConf conf, String dbName) throws Exception { Hive metastore = Hive.get(conf); metastore.dropDatabase(dbName, true, true, true); } private void createSummaryPartitions(CubeMetastoreClient client) throws Exception { String factName = "summary1"; CubeFactTable fact1 = client.getCubeFactTable(factName); createPIEParts(client, fact1, c2); factName = "summary2"; CubeFactTable fact2 = client.getCubeFactTable(factName); createPIEParts(client, fact2, c2); factName = "summary3"; CubeFactTable fact3 = client.getCubeFactTable(factName); createPIEParts(client, fact3, c2); factName = "summary4"; CubeFactTable fact4 = client.getCubeFactTable(factName); createPIEParts(client, fact4, c2); factName = "summary5"; CubeFactTable fact5 = client.getCubeFactTable(factName); createPIParts(client, fact5, c98); } private void createBaseCubeFactPartitions(CubeMetastoreClient client) throws HiveException, LensException { String factName = "testFact5_RAW_BASE"; CubeFactTable fact = client.getCubeFactTable(factName); // Add all hourly partitions for two days Calendar cal = Calendar.getInstance(); cal.setTime(TWODAYS_BACK); Date temp = cal.getTime(); while (!(temp.after(NOW))) { Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put("dt", temp); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, c1, CubeTableType.FACT); cal.add(HOUR_OF_DAY, 1); temp = cal.getTime(); } } private void createPIEParts(CubeMetastoreClient client, CubeFactTable fact, String storageName) throws Exception { // Add partitions in PIE storage Calendar pcal = Calendar.getInstance(); pcal.setTime(TWODAYS_BACK); pcal.set(HOUR_OF_DAY, 0); Calendar ical = Calendar.getInstance(); ical.setTime(TWODAYS_BACK); ical.set(HOUR_OF_DAY, 0); Map<UpdatePeriod, TreeSet<Date>> pTimes = Maps.newHashMap(); pTimes.put(DAILY, Sets.<Date>newTreeSet()); pTimes.put(HOURLY, Sets.<Date>newTreeSet()); Map<UpdatePeriod, TreeSet<Date>> iTimes = Maps.newHashMap(); iTimes.put(DAILY, Sets.<Date>newTreeSet()); iTimes.put(HOURLY, Sets.<Date>newTreeSet()); Map<String, Map<UpdatePeriod, TreeSet<Date>>> times = Maps.newHashMap(); times.put("et", iTimes); times.put("it", iTimes); times.put("pt", pTimes); // pt=day1 and it=day1 // pt=day2-hour[0-3] it = day1-hour[20-23] // pt=day2 and it=day1 // pt=day2-hour[4-23] it = day2-hour[0-19] // pt=day2 and it=day2 // pt=day3-hour[0-3] it = day2-hour[20-23] // pt=day3-hour[4-23] it = day3-hour[0-19] for (int p = 1; p <= 3; p++) { Date ptime = pcal.getTime(); Date itime = ical.getTime(); Map<String, Date> timeParts = new HashMap<String, Date>(); if (p == 1) { // day1 timeParts.put("pt", ptime); timeParts.put("it", itime); timeParts.put("et", itime); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, DAILY); pTimes.get(DAILY).add(ptime); iTimes.get(DAILY).add(itime); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); pcal.add(DAY_OF_MONTH, 1); ical.add(HOUR_OF_DAY, 20); } else if (p == 2) { // day2 // pt=day2-hour[0-3] it = day1-hour[20-23] // pt=day2 and it=day1 // pt=day2-hour[4-23] it = day2-hour[0-19] // pt=day2 and it=day2 ptime = pcal.getTime(); itime = ical.getTime(); timeParts.put("pt", ptime); timeParts.put("it", itime); timeParts.put("et", itime); // pt=day2 and it=day1 StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, DAILY); pTimes.get(DAILY).add(ptime); iTimes.get(DAILY).add(itime); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); // pt=day2-hour[0-3] it = day1-hour[20-23] // pt=day2-hour[4-23] it = day2-hour[0-19] for (int i = 0; i < 24; i++) { ptime = pcal.getTime(); itime = ical.getTime(); timeParts.put("pt", ptime); timeParts.put("it", itime); timeParts.put("et", itime); sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); pTimes.get(HOURLY).add(ptime); iTimes.get(HOURLY).add(itime); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); pcal.add(HOUR_OF_DAY, 1); ical.add(HOUR_OF_DAY, 1); } // pt=day2 and it=day2 sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, DAILY); pTimes.get(DAILY).add(ptime); iTimes.get(DAILY).add(itime); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); } else if (p == 3) { // day3 // pt=day3-hour[0-3] it = day2-hour[20-23] // pt=day3-hour[4-23] it = day3-hour[0-19] for (int i = 0; i < 24; i++) { ptime = pcal.getTime(); itime = ical.getTime(); timeParts.put("pt", ptime); timeParts.put("it", itime); timeParts.put("et", itime); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); pTimes.get(HOURLY).add(ptime); iTimes.get(HOURLY).add(itime); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); pcal.add(HOUR_OF_DAY, 1); ical.add(HOUR_OF_DAY, 1); } } } String storageTableName = MetastoreUtil.getStorageTableName(fact.getName(), Storage.getPrefix( storageName)); Map<String, String> params = client.getTable(storageTableName).getParameters(); String prefix = MetastoreConstants.STORAGE_PFX + MetastoreConstants.PARTITION_TIMELINE_CACHE; assertEquals(params.get(prefix + "present"), "true"); for (String p : Arrays.asList("et", "it", "pt")) { assertTimeline(client, fact.getName(), storageName, MINUTELY, p, EndsAndHolesPartitionTimeline.class); for (UpdatePeriod up : Arrays.asList(DAILY, HOURLY)) { EndsAndHolesPartitionTimeline timeline = new EndsAndHolesPartitionTimeline(storageTableName, up, p); timeline.setFirst(TimePartition.of(up, times.get(p).get(up).first())); timeline.setLatest(TimePartition.of(up, times.get(p).get(up).last())); assertTimeline(client, fact.getName(), storageName, up, p, timeline); } } } private void createPIParts(CubeMetastoreClient client, CubeFactTable fact, String storageName) throws Exception { // Add partitions in PI storage //daily partition registered for pt=day1, it = day1 //hourly partitions registered for pt=day1-hours[0-23] it=day1-hours[0-23] Calendar pcal = Calendar.getInstance(); pcal.setTime(ONEDAY_BACK); pcal.set(HOUR_OF_DAY, 0); Calendar ical = Calendar.getInstance(); ical.setTime(ONEDAY_BACK); ical.set(HOUR_OF_DAY, 0); Date ptime = pcal.getTime(); Date itime = ical.getTime(); Map<String, Date> timeParts = new HashMap<String, Date>(); timeParts.put("pt", ptime); timeParts.put("it", itime); StoragePartitionDesc sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, DAILY); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); for (int i = 0; i < 24; i++) { ptime = pcal.getTime(); itime = ical.getTime(); timeParts.put("pt", ptime); timeParts.put("it", itime); sPartSpec = new StoragePartitionDesc(fact.getName(), timeParts, null, HOURLY); client.addPartition(sPartSpec, storageName, CubeTableType.FACT); pcal.add(HOUR_OF_DAY, 1); ical.add(HOUR_OF_DAY, 1); } } public static void printQueryAST(String query, String label) throws LensException { System.out.println("--" + label + "--AST--"); System.out.println("--query- " + query); HQLParser.printAST(HQLParser.parseHQL(query, new HiveConf())); } }
/* Copyright (C) 2013-2015 Computer Sciences Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ezbake.quarantine.client; import ezbake.base.thrift.Visibility; import ezbake.configuration.DirectoryConfigurationLoader; import ezbake.configuration.EzConfiguration; import ezbake.configuration.EzConfigurationLoaderException; import ezbake.configuration.constants.EzBakePropertyConstants; import ezbake.quarantine.thrift.*; import ezbakehelpers.ezconfigurationhelpers.application.EzBakeApplicationConfigurationHelper; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by nkhan on 4/15/14. */ public class QuarantineCmdLineTool { private static final Logger logger = LoggerFactory.getLogger(QuarantineCmdLineTool.class); @Option(name="-s", aliases = "--securityId", usage="The security ID to use for the Quarantine Client. This will override whatever is read in from EzConfiguration", required = false) private String securityId; private int id = 0; public void run() throws IOException, EzConfigurationLoaderException { Properties props = new EzConfiguration().getProperties(); if (!props.containsKey(EzBakePropertyConstants.ZOOKEEPER_CONNECTION_STRING)) { throw new RuntimeException("No EzConfiguration properties loaded. Make sure to set the " + DirectoryConfigurationLoader.EZCONFIGURATION_PROPERTY + " system property"); } if (securityId != null) { props.setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_ID, securityId); } if (new EzBakeApplicationConfigurationHelper(props).getSecurityID() == null) { throw new RuntimeException("No security ID set. Verify that security ID is set in properties or provide security ID with -s parameter"); } QuarantineClient client = new QuarantineClient(props); boolean optionsDisplayed; String input = ""; String selectedPipeline = ""; Scanner sc = new Scanner(System.in); while(!input.equals("exit")) { System.out.println("Enter pipeline name"); input = sc.nextLine(); selectedPipeline = input; optionsDisplayed = false; while(true) { //All items are listed for the selected pipe along with options List<QuarantineResult> items = null; //Selected pipeline is used for further commands //until explicitly changed by the user if (!optionsDisplayed) { items = loadItems(selectedPipeline, client); displayPipelineOptions(input); optionsDisplayed = true; } //See which option the user picked input = sc.nextLine(); logger.info("input: " + input); if(input.equalsIgnoreCase("V")){ items = loadItems(selectedPipeline, client); if(items !=null) printItems(items); else System.out.println("No items to display"); //User selected update status }else if (input.equalsIgnoreCase("U")) { System.out.println("Enter item id: "); input = sc.nextLine(); items = loadItems(selectedPipeline, client); //Update status command executed QuarantineResult item = getItemForId(items, input); if (item != null) { //Item for the id exists //Prompt user to enter a new valid status ObjectStatus status = getValidStatus(sc); if(status != null) { //Update the status client.updateStatus(item.id, status, ""); System.out.println("Status updated successfully"); } else { System.out.println("invalid option, exiting..."); input = "exit"; break; } } else { System.out.println("No item for id : " ); } } else if(input.equals("S")) { //Send to quarantine option was selected System.out.println("Adding metadata? y/n: "); input = sc.nextLine(); AdditionalMetadata additionalMetadata = new AdditionalMetadata(); while (input.equals("y")) { System.out.println("Enter key:"); String key = sc.nextLine(); System.out.println("Enter value:"); String value = sc.nextLine(); additionalMetadata.putToEntries(key, new MetadataEntry().setValue(value)); System.out.println("Adding metadata? y/n: "); input = sc.nextLine(); } handleSendToQuarantine(selectedPipeline, additionalMetadata, client); } else if(input.equals("C")) { //Change pipeline option was selected //break out of the inner loop break; } else if(input.equals("T")) { //Pump a bunch of data in for (int i = 0; i < 10000; i++) { handleSendToQuarantineSameError(selectedPipeline, client); } } else if(input.equals("E")) { //User executed exit command break //out of inner loop and change input //to exit ot break out of outer loop input = "exit"; break; } else { System.out.println("Invalid command"); displayPipelineOptions(input); } } } System.out.println("TERMINATED!"); System.exit(1); } private void handleSendToQuarantineSameError(String pipeline, QuarantineClient client) throws IOException { HTMLDocument doc = new HTMLDocument(++id, "content: " + id, new Date().toString()); System.out.println("Sending thrift data to quarantine. Type: " + doc.getClass().getSimpleName()); client.sendObjectToQuarantine(pipeline, "test-pipe", doc, new Visibility().setFormalVisibility("U"), "error msg", null); } private void handleSendToQuarantine(String pipeline, AdditionalMetadata additionalMetadata, QuarantineClient client) throws IOException { HTMLDocument doc = new HTMLDocument(++id, "content: " + id, new Date().toString()); System.out.println("Sending thrift data to quarantine. Type: " + doc.getClass().getSimpleName()); client.sendObjectToQuarantine(pipeline, "test-pipe", doc, new Visibility().setFormalVisibility("U"), "error msg " + id, additionalMetadata.getEntriesSize() > 0 ? additionalMetadata : null); } /** * Returns a status based on user input * @param sc scanner to read the user input from * @return a valid status or null if user chose to exit */ private ObjectStatus getValidStatus(Scanner sc) { while(true) { System.out.println("Enter new status: \n" + "A: Approved \n" + "R: Reject \n" + "E: Exit/Cancel status update"); String input = sc.nextLine(); if (input.equalsIgnoreCase("A")) { return ObjectStatus.APPROVED_FOR_REINGEST; } else if (input.equalsIgnoreCase("R")) { return ObjectStatus.ARCHIVED; } else if (input.equalsIgnoreCase("E")){ return null; } else { System.out.print("Invalid option."); } } } /** * Displays options for the selected pipeline * @param input the name of the selected pipeline */ private void displayPipelineOptions(String input) { System.out.println("Pipeline selected " + input); System.out.println("Options: "); System.out.println("C: Change Pipeline\n" + "V: View items\n" + "S: Send an item to quarantine\n" + "U: Update status for an item \n" + "T: Add a ton of data\n" + "E: exit\n"); } /** * Searches through the list of items to find the item * with the requested id * @param items list of items to search through * @param reqId the id to match * @return QuarantineResult if it is found for the provided id, null otherwise */ private QuarantineResult getItemForId(List<QuarantineResult> items, String reqId) { for(QuarantineResult item: items){ if(item.id.equals(reqId)) return item; } return null; } private List<QuarantineResult> loadItems(String pipeline, QuarantineClient client){ try { Set<ObjectStatus> statuses = new HashSet<>(); statuses.add(ObjectStatus.APPROVED_FOR_REINGEST); statuses.add(ObjectStatus.QUARANTINED); statuses.add(ObjectStatus.ARCHIVED); List<QuarantineResult> items = client.getObjectsForPipeline(pipeline, statuses, 0, (short)1000); return items; } catch (Exception e) { System.out.println("Error retrieving items " + e.getMessage()); return null; } } /** * Goes through the list of quarantine results items and prints each item * @param items list of items to print */ private void printItems(List<QuarantineResult> items) { for(QuarantineResult item : items){ printItem(item); } } /** * Pretty prints a single item * @param item the item to print */ private void printItem(QuarantineResult item) { StringBuilder sb = new StringBuilder(); sb.append("id: ").append(item.id).append('\n'); sb.append("status: ").append(getStatus(item.status)).append('\n'); sb.append("----Event info: \n").append(getEventInfo(item.events)).append('\n'); System.out.println(sb.toString()); } /** * Returns a string for pretty printing events * @param events the list of events to extract information from * @return formatted string */ private String getEventInfo(List<QuarantineEvent> events) { StringBuilder sb = new StringBuilder(); Integer eventCounter = 1; for(QuarantineEvent event : events) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); sb.append("Event # ").append(eventCounter).append('\n'); sb.append("timestamp: ").append(format.format(event.getTimestamp())).append('\n'); sb.append("error msg: ").append(event.event).append('\n'); eventCounter++; } return sb.toString(); } /** * Returns string representation of status * @param status status to check * @return string representation of status */ private String getStatus(ObjectStatus status) { switch (status){ case QUARANTINED: return "QUARANTINED"; case APPROVED_FOR_REINGEST: return "APPROVED_FOR_REINGEST"; case ARCHIVED: return "ARCHIVED"; default: return ""; } } public static void main(String[] args){ QuarantineCmdLineTool client = new QuarantineCmdLineTool(); CmdLineParser parser = new CmdLineParser(client); try { parser.parseArgument(args); client.run(); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(1); } } }
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.collect.Iterables.unmodifiableIterable; import static com.google.common.collect.Sets.newEnumSet; import static com.google.common.collect.Sets.newHashSet; import static com.google.common.collect.Sets.newLinkedHashSet; import static com.google.common.collect.Sets.powerSet; import static com.google.common.collect.Sets.unmodifiableNavigableSet; import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE; import static com.google.common.truth.Truth.assertThat; import static java.io.ObjectStreamConstants.TC_REFERENCE; import static java.io.ObjectStreamConstants.baseWireHandle; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Equivalence; import com.google.common.collect.testing.AnEnum; import com.google.common.collect.testing.IteratorTester; import com.google.common.collect.testing.MinimalIterable; import com.google.common.collect.testing.NavigableSetTestSuiteBuilder; import com.google.common.collect.testing.SafeTreeSet; import com.google.common.collect.testing.SetTestSuiteBuilder; import com.google.common.collect.testing.TestEnumSetGenerator; import com.google.common.collect.testing.TestStringSetGenerator; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionSize; import com.google.common.collect.testing.features.SetFeature; import com.google.common.testing.CollectorTester; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import com.google.common.testing.SerializableTester; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArraySet; import java.util.stream.Collector; import javax.annotation.Nullable; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for {@code Sets}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class SetsTest extends TestCase { private static final IteratorTester.KnownOrder KNOWN_ORDER = IteratorTester.KnownOrder.KNOWN_ORDER; private static final Collection<Integer> EMPTY_COLLECTION = Arrays.<Integer>asList(); private static final Collection<Integer> SOME_COLLECTION = Arrays.asList(0, 1, 1); private static final Iterable<Integer> SOME_ITERABLE = new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return SOME_COLLECTION.iterator(); } }; private static final List<Integer> LONGER_LIST = Arrays.asList(8, 6, 7, 5, 3, 0, 9); private static final Comparator<Integer> SOME_COMPARATOR = Collections.reverseOrder(); @GwtIncompatible // suite public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(SetsTest.class); suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { return Sets.newConcurrentHashSet(Arrays.asList(elements)); } }) .named("Sets.newConcurrentHashSet") .withFeatures(CollectionSize.ANY, SetFeature.GENERAL_PURPOSE) .createTestSuite()); suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { int size = elements.length; // Remove last element, if size > 1 Set<String> set1 = (size > 1) ? Sets.newHashSet( Arrays.asList(elements).subList(0, size - 1)) : Sets.newHashSet(elements); // Remove first element, if size > 0 Set<String> set2 = (size > 0) ? Sets.newHashSet( Arrays.asList(elements).subList(1, size)) : Sets.<String>newHashSet(); return Sets.union(set1, set2); } }) .named("Sets.union") .withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES) .createTestSuite()); suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { Set<String> set1 = Sets.newHashSet(elements); set1.add(samples().e3()); Set<String> set2 = Sets.newHashSet(elements); set2.add(samples().e4()); return Sets.intersection(set1, set2); } }) .named("Sets.intersection") .withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES) .createTestSuite()); suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { Set<String> set1 = Sets.newHashSet(elements); set1.add(samples().e3()); Set<String> set2 = Sets.newHashSet(samples().e3()); return Sets.difference(set1, set2); } }) .named("Sets.difference") .withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES) .createTestSuite()); suite.addTest(SetTestSuiteBuilder.using(new TestEnumSetGenerator() { @Override protected Set<AnEnum> create(AnEnum[] elements) { AnEnum[] otherElements = new AnEnum[elements.length - 1]; System.arraycopy( elements, 1, otherElements, 0, otherElements.length); return Sets.immutableEnumSet(elements[0], otherElements); } }) .named("Sets.immutableEnumSet") .withFeatures(CollectionSize.ONE, CollectionSize.SEVERAL, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { SafeTreeSet<String> set = new SafeTreeSet<String>(Arrays.asList(elements)); return Sets.unmodifiableNavigableSet(set); } @Override public List<String> order(List<String> insertionOrder) { return Ordering.natural().sortedCopy(insertionOrder); } }) .named("Sets.unmodifiableNavigableSet[TreeSet]") .withFeatures(CollectionSize.ANY, CollectionFeature.KNOWN_ORDER, CollectionFeature.SERIALIZABLE) .createTestSuite()); suite.addTest(testsForFilter()); suite.addTest(testsForFilterNoNulls()); suite.addTest(testsForFilterFiltered()); return suite; } @GwtIncompatible // suite private static Test testsForFilter() { return SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { Set<String> unfiltered = Sets.newLinkedHashSet(); unfiltered.add("yyy"); Collections.addAll(unfiltered, elements); unfiltered.add("zzz"); return Sets.filter(unfiltered, Collections2Test.NOT_YYY_ZZZ); } }) .named("Sets.filter") .withFeatures( CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY) .createTestSuite(); } @GwtIncompatible // suite private static Test testsForFilterNoNulls() { TestSuite suite = new TestSuite(); suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { Set<String> unfiltered = Sets.newLinkedHashSet(); unfiltered.add("yyy"); unfiltered.addAll(ImmutableList.copyOf(elements)); unfiltered.add("zzz"); return Sets.filter(unfiltered, Collections2Test.LENGTH_1); } }) .named("Sets.filter, no nulls") .withFeatures( CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); suite.addTest(NavigableSetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override public NavigableSet<String> create(String[] elements) { NavigableSet<String> unfiltered = Sets.newTreeSet(); unfiltered.add("yyy"); unfiltered.addAll(ImmutableList.copyOf(elements)); unfiltered.add("zzz"); return Sets.filter(unfiltered, Collections2Test.LENGTH_1); } @Override public List<String> order(List<String> insertionOrder) { return Ordering.natural().sortedCopy(insertionOrder); } }) .named("Sets.filter[NavigableSet]") .withFeatures( CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite()); return suite; } @GwtIncompatible // suite private static Test testsForFilterFiltered() { return SetTestSuiteBuilder.using(new TestStringSetGenerator() { @Override public Set<String> create(String[] elements) { Set<String> unfiltered = Sets.newLinkedHashSet(); unfiltered.add("yyy"); unfiltered.addAll(ImmutableList.copyOf(elements)); unfiltered.add("zzz"); unfiltered.add("abc"); return Sets.filter( Sets.filter(unfiltered, Collections2Test.LENGTH_1), Collections2Test.NOT_YYY_ZZZ); } }) .named("Sets.filter, filtered input") .withFeatures( CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.KNOWN_ORDER, CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES) .createTestSuite(); } private enum SomeEnum { A, B, C, D } public void testImmutableEnumSet() { Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); assertThat(units).containsExactly(SomeEnum.B, SomeEnum.D).inOrder(); try { units.remove(SomeEnum.B); fail("ImmutableEnumSet should throw an exception on remove()"); } catch (UnsupportedOperationException expected) {} try { units.add(SomeEnum.C); fail("ImmutableEnumSet should throw an exception on add()"); } catch (UnsupportedOperationException expected) {} } @GwtIncompatible // SerializableTester public void testImmutableEnumSet_serialized() { Set<SomeEnum> units = Sets.immutableEnumSet(SomeEnum.D, SomeEnum.B); assertThat(units).containsExactly(SomeEnum.B, SomeEnum.D).inOrder(); Set<SomeEnum> copy = SerializableTester.reserializeAndAssert(units); assertTrue(copy instanceof ImmutableEnumSet); } public void testImmutableEnumSet_fromIterable() { ImmutableSet<SomeEnum> none = Sets.immutableEnumSet(MinimalIterable.<SomeEnum>of()); assertThat(none).isEmpty(); ImmutableSet<SomeEnum> one = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.B)); assertThat(one).contains(SomeEnum.B); ImmutableSet<SomeEnum> two = Sets.immutableEnumSet(MinimalIterable.of(SomeEnum.D, SomeEnum.B)); assertThat(two).containsExactly(SomeEnum.B, SomeEnum.D).inOrder(); } @GwtIncompatible // java serialization not supported in GWT. public void testImmutableEnumSet_deserializationMakesDefensiveCopy() throws Exception { ImmutableSet<SomeEnum> original = Sets.immutableEnumSet(SomeEnum.A, SomeEnum.B); int handleOffset = 6; byte[] serializedForm = serializeWithBackReference(original, handleOffset); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedForm)); ImmutableSet<?> deserialized = (ImmutableSet<?>) in.readObject(); EnumSet<?> delegate = (EnumSet<?>) in.readObject(); assertEquals(original, deserialized); assertTrue(delegate.remove(SomeEnum.A)); assertTrue(deserialized.contains(SomeEnum.A)); } public void testToImmutableEnumSet() { Collector<AnEnum, ?, ImmutableSet<AnEnum>> collector = Sets.toImmutableEnumSet(); Equivalence<ImmutableSet<AnEnum>> equivalence = Equivalence.equals().onResultOf(ImmutableSet::asList); CollectorTester.of(collector, equivalence) .expectCollects(ImmutableSet.of(AnEnum.A, AnEnum.B, AnEnum.C, AnEnum.D), AnEnum.A, AnEnum.B, AnEnum.A, AnEnum.C, AnEnum.B, AnEnum.B, AnEnum.D); } @GwtIncompatible // java serialization not supported in GWT. private static byte[] serializeWithBackReference(Object original, int handleOffset) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(original); byte[] handle = toByteArray(baseWireHandle + handleOffset); byte[] ref = prepended(TC_REFERENCE, handle); bos.write(ref); return bos.toByteArray(); } private static byte[] prepended(byte b, byte[] array) { byte[] out = new byte[array.length + 1]; out[0] = b; System.arraycopy(array, 0, out, 1, array.length); return out; } @GwtIncompatible // java.nio.ByteBuffer private static byte[] toByteArray(int h) { return ByteBuffer.allocate(4).putInt(h).array(); } public void testNewEnumSet_empty() { EnumSet<SomeEnum> copy = newEnumSet(Collections.<SomeEnum>emptySet(), SomeEnum.class); assertEquals(EnumSet.noneOf(SomeEnum.class), copy); } public void testNewEnumSet_enumSet() { EnumSet<SomeEnum> set = EnumSet.of(SomeEnum.A, SomeEnum.D); assertEquals(set, newEnumSet(set, SomeEnum.class)); } public void testNewEnumSet_collection() { Set<SomeEnum> set = ImmutableSet.of(SomeEnum.B, SomeEnum.C); assertEquals(set, newEnumSet(set, SomeEnum.class)); } public void testNewEnumSet_iterable() { Set<SomeEnum> set = ImmutableSet.of(SomeEnum.A, SomeEnum.B, SomeEnum.C); assertEquals(set, newEnumSet(unmodifiableIterable(set), SomeEnum.class)); } public void testNewHashSetEmpty() { HashSet<Integer> set = Sets.newHashSet(); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetVarArgs() { HashSet<Integer> set = Sets.newHashSet(0, 1, 1); verifySetContents(set, Arrays.asList(0, 1)); } public void testNewHashSetFromCollection() { HashSet<Integer> set = Sets.newHashSet(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewHashSetFromIterable() { HashSet<Integer> set = Sets.newHashSet(SOME_ITERABLE); verifySetContents(set, SOME_ITERABLE); } public void testNewHashSetWithExpectedSizeSmall() { HashSet<Integer> set = Sets.newHashSetWithExpectedSize(0); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetWithExpectedSizeLarge() { HashSet<Integer> set = Sets.newHashSetWithExpectedSize(1000); verifySetContents(set, EMPTY_COLLECTION); } public void testNewHashSetFromIterator() { HashSet<Integer> set = Sets.newHashSet(SOME_COLLECTION.iterator()); verifySetContents(set, SOME_COLLECTION); } public void testNewConcurrentHashSetEmpty() { Set<Integer> set = Sets.newConcurrentHashSet(); verifySetContents(set, EMPTY_COLLECTION); } public void testNewConcurrentHashSetFromCollection() { Set<Integer> set = Sets.newConcurrentHashSet(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } public void testNewLinkedHashSetEmpty() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(); verifyLinkedHashSetContents(set, EMPTY_COLLECTION); } public void testNewLinkedHashSetFromCollection() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(LONGER_LIST); verifyLinkedHashSetContents(set, LONGER_LIST); } public void testNewLinkedHashSetFromIterable() { LinkedHashSet<Integer> set = Sets.newLinkedHashSet(new Iterable<Integer>() { @Override public Iterator<Integer> iterator() { return LONGER_LIST.iterator(); } }); verifyLinkedHashSetContents(set, LONGER_LIST); } public void testNewLinkedHashSetWithExpectedSizeSmall() { LinkedHashSet<Integer> set = Sets.newLinkedHashSetWithExpectedSize(0); verifySetContents(set, EMPTY_COLLECTION); } public void testNewLinkedHashSetWithExpectedSizeLarge() { LinkedHashSet<Integer> set = Sets.newLinkedHashSetWithExpectedSize(1000); verifySetContents(set, EMPTY_COLLECTION); } public void testNewTreeSetEmpty() { TreeSet<Integer> set = Sets.newTreeSet(); verifySortedSetContents(set, EMPTY_COLLECTION, null); } public void testNewTreeSetEmptyDerived() { TreeSet<Derived> set = Sets.newTreeSet(); assertTrue(set.isEmpty()); set.add(new Derived("foo")); set.add(new Derived("bar")); assertThat(set).containsExactly(new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetEmptyNonGeneric() { TreeSet<LegacyComparable> set = Sets.newTreeSet(); assertTrue(set.isEmpty()); set.add(new LegacyComparable("foo")); set.add(new LegacyComparable("bar")); assertThat(set).containsExactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeSetFromCollection() { TreeSet<Integer> set = Sets.newTreeSet(SOME_COLLECTION); verifySortedSetContents(set, SOME_COLLECTION, null); } public void testNewTreeSetFromIterable() { TreeSet<Integer> set = Sets.newTreeSet(SOME_ITERABLE); verifySortedSetContents(set, SOME_ITERABLE, null); } public void testNewTreeSetFromIterableDerived() { Iterable<Derived> iterable = Arrays.asList(new Derived("foo"), new Derived("bar")); TreeSet<Derived> set = Sets.newTreeSet(iterable); assertThat(set).containsExactly( new Derived("bar"), new Derived("foo")).inOrder(); } public void testNewTreeSetFromIterableNonGeneric() { Iterable<LegacyComparable> iterable = Arrays.asList(new LegacyComparable("foo"), new LegacyComparable("bar")); TreeSet<LegacyComparable> set = Sets.newTreeSet(iterable); assertThat(set).containsExactly( new LegacyComparable("bar"), new LegacyComparable("foo")).inOrder(); } public void testNewTreeSetEmptyWithComparator() { TreeSet<Integer> set = Sets.newTreeSet(SOME_COMPARATOR); verifySortedSetContents(set, EMPTY_COLLECTION, SOME_COMPARATOR); } public void testNewIdentityHashSet() { Set<Integer> set = Sets.newIdentityHashSet(); Integer value1 = new Integer(12357); Integer value2 = new Integer(12357); assertTrue(set.add(value1)); assertFalse(set.contains(value2)); assertTrue(set.contains(value1)); assertTrue(set.add(value2)); assertEquals(2, set.size()); } @GwtIncompatible // CopyOnWriteArraySet public void testNewCOWASEmpty() { CopyOnWriteArraySet<Integer> set = Sets.newCopyOnWriteArraySet(); verifySetContents(set, EMPTY_COLLECTION); } @GwtIncompatible // CopyOnWriteArraySet public void testNewCOWASFromIterable() { CopyOnWriteArraySet<Integer> set = Sets.newCopyOnWriteArraySet(SOME_ITERABLE); verifySetContents(set, SOME_COLLECTION); } public void testComplementOfEnumSet() { Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfEnumSetWithType() { Set<SomeEnum> units = EnumSet.of(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfRegularSet() { Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfRegularSetWithType() { Set<SomeEnum> units = Sets.newHashSet(SomeEnum.B, SomeEnum.D); EnumSet<SomeEnum> otherUnits = Sets.complementOf(units, SomeEnum.class); verifySetContents(otherUnits, EnumSet.of(SomeEnum.A, SomeEnum.C)); } public void testComplementOfEmptySet() { Set<SomeEnum> noUnits = Collections.emptySet(); EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits, SomeEnum.class); verifySetContents(EnumSet.allOf(SomeEnum.class), allUnits); } public void testComplementOfFullSet() { Set<SomeEnum> allUnits = Sets.newHashSet(SomeEnum.values()); EnumSet<SomeEnum> noUnits = Sets.complementOf(allUnits, SomeEnum.class); verifySetContents(noUnits, EnumSet.noneOf(SomeEnum.class)); } public void testComplementOfEmptyEnumSetWithoutType() { Set<SomeEnum> noUnits = EnumSet.noneOf(SomeEnum.class); EnumSet<SomeEnum> allUnits = Sets.complementOf(noUnits); verifySetContents(allUnits, EnumSet.allOf(SomeEnum.class)); } public void testComplementOfEmptySetWithoutTypeDoesntWork() { Set<SomeEnum> set = Collections.emptySet(); try { Sets.complementOf(set); fail(); } catch (IllegalArgumentException expected) {} } @GwtIncompatible // NullPointerTester public void testNullPointerExceptions() { new NullPointerTester() .setDefault(Enum.class, SomeEnum.A) .setDefault(Class.class, SomeEnum.class) // for newEnumSet .testAllPublicStaticMethods(Sets.class); } public void testNewSetFromMap() { Set<Integer> set = Sets.newSetFromMap(new HashMap<Integer, Boolean>()); set.addAll(SOME_COLLECTION); verifySetContents(set, SOME_COLLECTION); } @GwtIncompatible // SerializableTester public void testNewSetFromMapSerialization() { Set<Integer> set = Sets.newSetFromMap(new LinkedHashMap<Integer, Boolean>()); set.addAll(SOME_COLLECTION); Set<Integer> copy = SerializableTester.reserializeAndAssert(set); assertThat(copy).containsExactly(0, 1).inOrder(); } public void testNewSetFromMapIllegal() { Map<Integer, Boolean> map = new LinkedHashMap<Integer, Boolean>(); map.put(2, true); try { Sets.newSetFromMap(map); fail(); } catch (IllegalArgumentException expected) {} } // TODO: the overwhelming number of suppressions below suggests that maybe // it's not worth having a varargs form of this method at all... /** * The 0-ary cartesian product is a single empty list. */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_zeroary() { assertThat(Sets.cartesianProduct()).containsExactly(list()); } /** * A unary cartesian product is one list of size 1 for each element in the * input set. */ @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unary() { assertThat(Sets.cartesianProduct(set(1, 2))).containsExactly(list(1), list(2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary0x0() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(mt, mt)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary0x1() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(mt, set(1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x0() { Set<Integer> mt = emptySet(); assertEmpty(Sets.cartesianProduct(set(1), mt)); } private static void assertEmpty(Set<? extends List<?>> set) { assertTrue(set.isEmpty()); assertEquals(0, set.size()); assertFalse(set.iterator().hasNext()); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x1() { assertThat(Sets.cartesianProduct(set(1), set(2))).contains(list(1, 2)); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary1x2() { assertThat(Sets.cartesianProduct(set(1), set(2, 3))) .containsExactly(list(1, 2), list(1, 3)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_binary2x2() { assertThat(Sets.cartesianProduct(set(1, 2), set(3, 4))) .containsExactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_2x2x2() { assertThat(Sets.cartesianProduct(set(0, 1), set(0, 1), set(0, 1))).containsExactly( list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1), list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_contains() { Set<List<Integer>> actual = Sets.cartesianProduct(set(1, 2), set(3, 4)); assertTrue(actual.contains(list(1, 3))); assertTrue(actual.contains(list(1, 4))); assertTrue(actual.contains(list(2, 3))); assertTrue(actual.contains(list(2, 4))); assertFalse(actual.contains(list(3, 1))); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_unrelatedTypes() { Set<Integer> x = set(1, 2); Set<String> y = set("3", "4"); List<Object> exp1 = list((Object) 1, "3"); List<Object> exp2 = list((Object) 1, "4"); List<Object> exp3 = list((Object) 2, "3"); List<Object> exp4 = list((Object) 2, "4"); assertThat(Sets.<Object>cartesianProduct(x, y)) .containsExactly(exp1, exp2, exp3, exp4).inOrder(); } @SuppressWarnings("unchecked") // varargs! public void testCartesianProductTooBig() { Set<Integer> set = ContiguousSet.create(Range.closed(0, 10000), DiscreteDomain.integers()); try { Sets.cartesianProduct(set, set, set, set, set); fail("Expected IAE"); } catch (IllegalArgumentException expected) { } } @SuppressWarnings("unchecked") // varargs! public void testCartesianProduct_hashCode() { // Run through the same cartesian products we tested above Set<List<Integer>> degenerate = Sets.cartesianProduct(); checkHashCode(degenerate); checkHashCode(Sets.cartesianProduct(set(1, 2))); int num = Integer.MAX_VALUE / 3 * 2; // tickle overflow-related problems checkHashCode(Sets.cartesianProduct(set(1, 2, num))); Set<Integer> mt = emptySet(); checkHashCode(Sets.cartesianProduct(mt, mt)); checkHashCode(Sets.cartesianProduct(mt, set(num))); checkHashCode(Sets.cartesianProduct(set(num), mt)); checkHashCode(Sets.cartesianProduct(set(num), set(1))); checkHashCode(Sets.cartesianProduct(set(1), set(2, num))); checkHashCode(Sets.cartesianProduct(set(1, num), set(2, num - 1))); checkHashCode(Sets.cartesianProduct( set(1, num), set(2, num - 1), set(3, num + 1))); // a bigger one checkHashCode(Sets.cartesianProduct( set(1, num, num + 1), set(2), set(3, num + 2), set(4, 5, 6, 7, 8))); } public void testPowerSetEmpty() { ImmutableSet<Integer> elements = ImmutableSet.of(); Set<Set<Integer>> powerSet = powerSet(elements); assertEquals(1, powerSet.size()); assertEquals(ImmutableSet.of(ImmutableSet.of()), powerSet); assertEquals(0, powerSet.hashCode()); } public void testPowerSetContents() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2, 3); Set<Set<Integer>> powerSet = powerSet(elements); assertEquals(8, powerSet.size()); assertEquals(4 * 1 + 4 * 2 + 4 * 3, powerSet.hashCode()); Set<Set<Integer>> expected = newHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(3)); expected.add(ImmutableSet.of(1, 2)); expected.add(ImmutableSet.of(1, 3)); expected.add(ImmutableSet.of(2, 3)); expected.add(ImmutableSet.of(1, 2, 3)); Set<Set<Integer>> almostPowerSet = newHashSet(expected); almostPowerSet.remove(ImmutableSet.of(1, 2, 3)); almostPowerSet.add(ImmutableSet.of(1, 2, 4)); new EqualsTester() .addEqualityGroup(expected, powerSet) .addEqualityGroup(ImmutableSet.of(1, 2, 3)) .addEqualityGroup(almostPowerSet) .testEquals(); for (Set<Integer> subset : expected) { assertTrue(powerSet.contains(subset)); } assertFalse(powerSet.contains(ImmutableSet.of(1, 2, 4))); assertFalse(powerSet.contains(singleton(null))); assertFalse(powerSet.contains(null)); assertFalse(powerSet.contains((Object) "notASet")); } public void testPowerSetIteration_manual() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2, 3); Set<Set<Integer>> powerSet = powerSet(elements); // The API doesn't promise this iteration order, but it's convenient here. Iterator<Set<Integer>> i = powerSet.iterator(); assertEquals(ImmutableSet.of(), i.next()); assertEquals(ImmutableSet.of(1), i.next()); assertEquals(ImmutableSet.of(2), i.next()); assertEquals(ImmutableSet.of(2, 1), i.next()); assertEquals(ImmutableSet.of(3), i.next()); assertEquals(ImmutableSet.of(3, 1), i.next()); assertEquals(ImmutableSet.of(3, 2), i.next()); assertEquals(ImmutableSet.of(3, 2, 1), i.next()); assertFalse(i.hasNext()); try { i.next(); fail(); } catch (NoSuchElementException expected) { } } @GwtIncompatible // too slow for GWT public void testPowerSetIteration_iteratorTester() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2); Set<Set<Integer>> expected = newLinkedHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(1, 2)); final Set<Set<Integer>> powerSet = powerSet(elements); new IteratorTester<Set<Integer>>(6, UNMODIFIABLE, expected, KNOWN_ORDER) { @Override protected Iterator<Set<Integer>> newTargetIterator() { return powerSet.iterator(); } }.test(); } public void testPowerSetIteration_iteratorTester_fast() { ImmutableSet<Integer> elements = ImmutableSet.of(1, 2); Set<Set<Integer>> expected = newLinkedHashSet(); expected.add(ImmutableSet.<Integer>of()); expected.add(ImmutableSet.of(1)); expected.add(ImmutableSet.of(2)); expected.add(ImmutableSet.of(1, 2)); final Set<Set<Integer>> powerSet = powerSet(elements); new IteratorTester<Set<Integer>>(4, UNMODIFIABLE, expected, KNOWN_ORDER) { @Override protected Iterator<Set<Integer>> newTargetIterator() { return powerSet.iterator(); } }.test(); } public void testPowerSetSize() { assertPowerSetSize(1); assertPowerSetSize(2, 'a'); assertPowerSetSize(4, 'a', 'b'); assertPowerSetSize(8, 'a', 'b', 'c'); assertPowerSetSize(16, 'a', 'b', 'd', 'e'); assertPowerSetSize(1 << 30, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4'); } public void testPowerSetCreationErrors() { try { Set<Set<Character>> unused = powerSet( newHashSet( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5')); fail(); } catch (IllegalArgumentException expected) { } try { powerSet(singleton(null)); fail(); } catch (NullPointerException expected) { } } public void testPowerSetEqualsAndHashCode_verifyAgainstHashSet() { ImmutableList<Integer> allElements = ImmutableList.of(4233352, 3284593, 3794208, 3849533, 4013967, 2902658, 1886275, 2131109, 985872, 1843868); for (int i = 0; i < allElements.size(); i++) { Set<Integer> elements = newHashSet(allElements.subList(0, i)); Set<Set<Integer>> powerSet1 = powerSet(elements); Set<Set<Integer>> powerSet2 = powerSet(elements); new EqualsTester() .addEqualityGroup(powerSet1, powerSet2, toHashSets(powerSet1)) .addEqualityGroup(ImmutableSet.of()) .addEqualityGroup(ImmutableSet.of(9999999)) .addEqualityGroup("notASet") .testEquals(); assertEquals(toHashSets(powerSet1).hashCode(), powerSet1.hashCode()); } } /** * Test that a hash code miscomputed by "input.hashCode() * tooFarValue / 2" * is correct under our {@code hashCode} implementation. */ public void testPowerSetHashCode_inputHashCodeTimesTooFarValueIsZero() { Set<Object> sumToEighthMaxIntElements = newHashSet(objectWithHashCode(1 << 29), objectWithHashCode(0)); assertPowerSetHashCode(1 << 30, sumToEighthMaxIntElements); Set<Object> sumToQuarterMaxIntElements = newHashSet(objectWithHashCode(1 << 30), objectWithHashCode(0)); assertPowerSetHashCode(1 << 31, sumToQuarterMaxIntElements); } public void testPowerSetShowOff() { Set<Object> zero = ImmutableSet.of(); Set<Set<Object>> one = powerSet(zero); Set<Set<Set<Object>>> two = powerSet(one); Set<Set<Set<Set<Object>>>> four = powerSet(two); Set<Set<Set<Set<Set<Object>>>>> sixteen = powerSet(four); Set<Set<Set<Set<Set<Set<Object>>>>>> sixtyFiveThousandish = powerSet(sixteen); assertEquals(1 << 16, sixtyFiveThousandish.size()); assertTrue(powerSet(makeSetOfZeroToTwentyNine()) .contains(makeSetOfZeroToTwentyNine())); assertFalse(powerSet(makeSetOfZeroToTwentyNine()) .contains(ImmutableSet.of(30))); } private static Set<Integer> makeSetOfZeroToTwentyNine() { // TODO: use Range once it's publicly available Set<Integer> zeroToTwentyNine = newHashSet(); for (int i = 0; i < 30; i++) { zeroToTwentyNine.add(i); } return zeroToTwentyNine; } private static <E> Set<Set<E>> toHashSets(Set<Set<E>> powerSet) { Set<Set<E>> result = newHashSet(); for (Set<E> subset : powerSet) { result.add(new HashSet<E>(subset)); } return result; } private static Object objectWithHashCode(final int hashCode) { return new Object() { @Override public int hashCode() { return hashCode; } }; } private static void assertPowerSetHashCode(int expected, Set<?> elements) { assertEquals(expected, powerSet(elements).hashCode()); } private static void assertPowerSetSize(int i, Object... elements) { assertEquals(i, powerSet(newHashSet(elements)).size()); } private static void checkHashCode(Set<?> set) { assertEquals(Sets.newHashSet(set).hashCode(), set.hashCode()); } private static <E> Set<E> set(E... elements) { return ImmutableSet.copyOf(elements); } private static <E> List<E> list(E... elements) { return ImmutableList.copyOf(elements); } /** * Utility method to verify that the given LinkedHashSet is equal to and * hashes identically to a set constructed with the elements in the given * collection. Also verifies that the ordering in the set is the same * as the ordering of the given contents. */ private static <E> void verifyLinkedHashSetContents( LinkedHashSet<E> set, Collection<E> contents) { assertEquals("LinkedHashSet should have preserved order for iteration", new ArrayList<E>(set), new ArrayList<E>(contents)); verifySetContents(set, contents); } /** * Utility method to verify that the given SortedSet is equal to and * hashes identically to a set constructed with the elements in the * given iterable. Also verifies that the comparator is the same as the * given comparator. */ private static <E> void verifySortedSetContents( SortedSet<E> set, Iterable<E> iterable, @Nullable Comparator<E> comparator) { assertSame(comparator, set.comparator()); verifySetContents(set, iterable); } /** * Utility method that verifies that the given set is equal to and hashes * identically to a set constructed with the elements in the given iterable. */ private static <E> void verifySetContents(Set<E> set, Iterable<E> contents) { Set<E> expected = null; if (contents instanceof Set) { expected = (Set<E>) contents; } else { expected = new HashSet<E>(); for (E element : contents) { expected.add(element); } } assertEquals(expected, set); } /** * Simple base class to verify that we handle generics correctly. */ static class Base implements Comparable<Base>, Serializable { private final String s; public Base(String s) { this.s = s; } @Override public int hashCode() { // delegate to 's' return s.hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } else if (other instanceof Base) { return s.equals(((Base) other).s); } else { return false; } } @Override public int compareTo(Base o) { return s.compareTo(o.s); } private static final long serialVersionUID = 0; } /** * Simple derived class to verify that we handle generics correctly. */ static class Derived extends Base { public Derived(String s) { super(s); } private static final long serialVersionUID = 0; } @GwtIncompatible // NavigableSet public void testUnmodifiableNavigableSet() { TreeSet<Integer> mod = Sets.newTreeSet(); mod.add(1); mod.add(2); mod.add(3); NavigableSet<Integer> unmod = unmodifiableNavigableSet(mod); /* Unmodifiable is a view. */ mod.add(4); assertTrue(unmod.contains(4)); assertTrue(unmod.descendingSet().contains(4)); ensureNotDirectlyModifiable(unmod); ensureNotDirectlyModifiable(unmod.descendingSet()); ensureNotDirectlyModifiable(unmod.headSet(2)); ensureNotDirectlyModifiable(unmod.headSet(2, true)); ensureNotDirectlyModifiable(unmod.tailSet(2)); ensureNotDirectlyModifiable(unmod.tailSet(2, true)); ensureNotDirectlyModifiable(unmod.subSet(1, 3)); ensureNotDirectlyModifiable(unmod.subSet(1, true, 3, true)); /* UnsupportedOperationException on indirect modifications. */ NavigableSet<Integer> reverse = unmod.descendingSet(); try { reverse.add(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { reverse.addAll(Collections.singleton(4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { reverse.remove(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } } void ensureNotDirectlyModifiable(SortedSet<Integer> unmod) { try { unmod.add(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.remove(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.addAll(Collections.singleton(4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { Iterator<Integer> iterator = unmod.iterator(); iterator.next(); iterator.remove(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } } @GwtIncompatible // NavigableSet void ensureNotDirectlyModifiable(NavigableSet<Integer> unmod) { try { unmod.add(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.remove(4); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.addAll(Collections.singleton(4)); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.pollFirst(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { unmod.pollLast(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { Iterator<Integer> iterator = unmod.iterator(); iterator.next(); iterator.remove(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } try { Iterator<Integer> iterator = unmod.descendingIterator(); iterator.next(); iterator.remove(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException expected) { } } @GwtIncompatible // NavigableSet public void testSubSet_boundedRange() { ImmutableSortedSet<Integer> set = ImmutableSortedSet.of(2, 4, 6, 8, 10); ImmutableSortedSet<Integer> empty = ImmutableSortedSet.of(); assertEquals(set, Sets.subSet(set, Range.closed(0, 12))); assertEquals(ImmutableSortedSet.of(2, 4), Sets.subSet(set, Range.closed(0, 4))); assertEquals(ImmutableSortedSet.of(2, 4, 6), Sets.subSet(set, Range.closed(2, 6))); assertEquals(ImmutableSortedSet.of(4, 6), Sets.subSet(set, Range.closed(3, 7))); assertEquals(empty, Sets.subSet(set, Range.closed(20, 30))); assertEquals(set, Sets.subSet(set, Range.open(0, 12))); assertEquals(ImmutableSortedSet.of(2), Sets.subSet(set, Range.open(0, 4))); assertEquals(ImmutableSortedSet.of(4), Sets.subSet(set, Range.open(2, 6))); assertEquals(ImmutableSortedSet.of(4, 6), Sets.subSet(set, Range.open(3, 7))); assertEquals(empty, Sets.subSet(set, Range.open(20, 30))); assertEquals(set, Sets.subSet(set, Range.openClosed(0, 12))); assertEquals(ImmutableSortedSet.of(2, 4), Sets.subSet(set, Range.openClosed(0, 4))); assertEquals(ImmutableSortedSet.of(4, 6), Sets.subSet(set, Range.openClosed(2, 6))); assertEquals(ImmutableSortedSet.of(4, 6), Sets.subSet(set, Range.openClosed(3, 7))); assertEquals(empty, Sets.subSet(set, Range.openClosed(20, 30))); assertEquals(set, Sets.subSet(set, Range.closedOpen(0, 12))); assertEquals(ImmutableSortedSet.of(2), Sets.subSet(set, Range.closedOpen(0, 4))); assertEquals(ImmutableSortedSet.of(2, 4), Sets.subSet(set, Range.closedOpen(2, 6))); assertEquals(ImmutableSortedSet.of(4, 6), Sets.subSet(set, Range.closedOpen(3, 7))); assertEquals(empty, Sets.subSet(set, Range.closedOpen(20, 30))); } @GwtIncompatible // NavigableSet public void testSubSet_halfBoundedRange() { ImmutableSortedSet<Integer> set = ImmutableSortedSet.of(2, 4, 6, 8, 10); ImmutableSortedSet<Integer> empty = ImmutableSortedSet.of(); assertEquals(set, Sets.subSet(set, Range.atLeast(0))); assertEquals(ImmutableSortedSet.of(4, 6, 8, 10), Sets.subSet(set, Range.atLeast(4))); assertEquals(ImmutableSortedSet.of(8, 10), Sets.subSet(set, Range.atLeast(7))); assertEquals(empty, Sets.subSet(set, Range.atLeast(20))); assertEquals(set, Sets.subSet(set, Range.greaterThan(0))); assertEquals(ImmutableSortedSet.of(6, 8, 10), Sets.subSet(set, Range.greaterThan(4))); assertEquals(ImmutableSortedSet.of(8, 10), Sets.subSet(set, Range.greaterThan(7))); assertEquals(empty, Sets.subSet(set, Range.greaterThan(20))); assertEquals(empty, Sets.subSet(set, Range.lessThan(0))); assertEquals(ImmutableSortedSet.of(2), Sets.subSet(set, Range.lessThan(4))); assertEquals(ImmutableSortedSet.of(2, 4, 6), Sets.subSet(set, Range.lessThan(7))); assertEquals(set, Sets.subSet(set, Range.lessThan(20))); assertEquals(empty, Sets.subSet(set, Range.atMost(0))); assertEquals(ImmutableSortedSet.of(2, 4), Sets.subSet(set, Range.atMost(4))); assertEquals(ImmutableSortedSet.of(2, 4, 6), Sets.subSet(set, Range.atMost(7))); assertEquals(set, Sets.subSet(set, Range.atMost(20))); } @GwtIncompatible // NavigableSet public void testSubSet_unboundedRange() { ImmutableSortedSet<Integer> set = ImmutableSortedSet.of(2, 4, 6, 8, 10); assertEquals(set, Sets.subSet(set, Range.<Integer>all())); } @GwtIncompatible // NavigableSet public void testSubSet_unnaturalOrdering() { ImmutableSortedSet<Integer> set = ImmutableSortedSet.<Integer>reverseOrder().add(2, 4, 6, 8, 10).build(); try { Sets.subSet(set, Range.closed(4, 8)); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException expected) { } // These results are all incorrect, but there's no way (short of iterating over the result) // to verify that with an arbitrary ordering or comparator. assertEquals(ImmutableSortedSet.of(2, 4), Sets.subSet(set, Range.atLeast(4))); assertEquals(ImmutableSortedSet.of(8, 10), Sets.subSet(set, Range.atMost(8))); assertEquals(ImmutableSortedSet.of(2, 4, 6, 8, 10), Sets.subSet(set, Range.<Integer>all())); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Oleg V. Khaschansky * @version $Revision$ * * @date: Nov 22, 2005 */ package org.apache.harmony.awt.gl.linux; import java.awt.*; import java.awt.image.IndexColorModel; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import org.apache.harmony.awt.gl.CommonGraphics2D; import org.apache.harmony.awt.gl.MultiRectArea; import org.apache.harmony.awt.gl.Surface; import org.apache.harmony.awt.gl.Utils; import org.apache.harmony.awt.gl.font.LinuxNativeFont; import org.apache.harmony.awt.wtk.NativeWindow; import org.apache.harmony.awt.nativebridge.Int8Pointer; import org.apache.harmony.awt.nativebridge.NativeBridge; import org.apache.harmony.awt.nativebridge.linux.X11; import org.apache.harmony.awt.nativebridge.linux.Xft; import org.apache.harmony.awt.nativebridge.linux.X11Defs; public class XGraphics2D extends CommonGraphics2D { private static final X11 x11 = X11.getInstance(); private static final Xft xft = Xft.getInstance(); long drawable; // X11 window or pixmap long display; long xftDraw; // Context related long gc; // X11 GC for basic drawing long imageGC; // X11 GC for image operations int argb; XGraphicsConfiguration xConfig; boolean nativeLines = true; boolean nativePaint = true; boolean transparentColor = false; boolean scalingTransform = false; boolean simpleComposite = true; boolean indexModel = false; public XGraphics2D(long drawable, int tx, int ty, MultiRectArea clip) { super(tx, ty, clip); this.drawable = drawable; xConfig = (XGraphicsConfiguration) getDeviceConfiguration(); display = xConfig.dev.display; gc = createGC(display, drawable); X11.Visual visual = xConfig.info.get_visual(); xftDraw = createXftDraw(display, drawable, visual.lock()); visual.unlock(); imageGC = createGC(display, drawable); //xSetForeground(argb); // Set default foregroung to black blitter = XBlitter.getInstance(); Rectangle bounds = clip.getBounds(); dstSurf = new XSurface(this, bounds.width, bounds.height); jtr = DrawableTextRenderer.inst; //setTransformedClip(clip); setClip(clip); if (xConfig.getColorModel() instanceof IndexColorModel) { indexModel = true; } } public XGraphics2D(long drawable, int tx, int ty, int width, int height) { this(drawable, tx, ty, new MultiRectArea(new Rectangle(width, height))); } public XGraphics2D(NativeWindow nwin, int tx, int ty, MultiRectArea clip) { this(nwin.getId(), tx, ty, clip); } public XGraphics2D(NativeWindow nwin, int tx, int ty, int width, int height) { this(nwin.getId(), tx, ty, new MultiRectArea(new Rectangle(width, height))); } public Graphics create() { XGraphics2D res = new XGraphics2D( drawable, origPoint.x, origPoint.y, dstSurf.getWidth(), dstSurf.getHeight() ); copyInternalFields(res); return res; } public long createXftDraw(long display, long drawable, long visual){ long draw = LinuxNativeFont.createXftDrawNative(display, drawable, visual); LinuxNativeFont.xftDrawSetSubwindowModeNative(draw, X11Defs.IncludeInferiors); return draw; } private static final long createGC(long display, long win) { return x11.XCreateGC(display, win, 0, 0); } public GraphicsConfiguration getDeviceConfiguration() { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); return env.getDefaultScreenDevice().getDefaultConfiguration(); } public void copyArea(int x, int y, int width, int height, int dx, int dy) { x += transform.getTranslateX(); y += transform.getTranslateY(); x11.XCopyArea(display, drawable, drawable, gc, x, y, width, height, dx+x, dy+y); } // Caller should free native pointer to rects after using it private static final X11.XRectangle createXRects(int[] vertices) { int rectsSize = (vertices[0]-1) << 1; // sizeof(XRectangle) = 8 Int8Pointer rects = NativeBridge.getInstance().createInt8Pointer(rectsSize, true); int idx = 0; for (int i = 1; i < vertices[0]; i+=4) { X11.XRectangle r = x11.createXRectangle(rects.getElementPointer(idx)); r.set_x((short) vertices[i]); r.set_y((short) vertices[i+1]); r.set_width((short) (vertices[i+2]-vertices[i]+1)); r.set_height((short) (vertices[i+3]-vertices[i+1]+1)); idx += r.size(); } return x11.createXRectangle(rects); } protected void fillMultiRectAreaColor(MultiRectArea mra) { if (transparentColor || !simpleComposite) { super.fillMultiRectAreaColor(mra); } else { int vertices[] = mra.rect; int nRects = (vertices[0]-1) >> 2; X11.XRectangle xRects = createXRects(vertices); x11.XFillRectangles(display, drawable, gc, xRects, nRects); xRects.free(); } } public void setPaint(Paint paint) { if (paint == null) return; if (paint instanceof Color) { setColor((Color)paint); nativePaint = true; } else { super.setPaint(paint); nativePaint = false; } } public void setColor(Color color) { if (color == null) return; super.setColor(color); // Get values for XColor int argb_val = color.getRGB(); if (argb_val != argb) { // Check if it is a transparent color if ((argb_val & 0xFF000000) != 0xFF000000) transparentColor = true; else transparentColor = false; xSetForeground(argb_val); } } private void xSetForeground(int argb_val) { // XAllocColor doesn't match closest color, // get the exact value from ColorModel if (indexModel) { IndexColorModel icm = (IndexColorModel) xConfig.getColorModel(); int pixel = ((int[]) icm.getDataElements(argb_val, new int[]{0}))[0]; argb_val = icm.getRGB(pixel); } short xRed = (short) ((argb_val & 0x00FF0000) >> 8); short xGreen = (short) (argb_val & 0x0000FF00); short xBlue = (short) ((argb_val & 0x000000FF) << 8); // Create XColor X11.XColor xcolor = x11.createXColor(true); xcolor.set_red(xRed); xcolor.set_green(xGreen); xcolor.set_blue(xBlue); // Allocate cmap cell x11.XAllocColor(display, xConfig.xcolormap, xcolor); x11.XSetForeground(display, gc, xcolor.get_pixel()); // Cleanup xcolor.free(); } public void dispose() { super.dispose(); if (xftDraw != 0) { LinuxNativeFont.freeXftDrawNative(this.xftDraw); xftDraw = 0; } if (gc != 0) { x11.XFreeGC(display, gc); gc = 0; } if (imageGC != 0) { x11.XFreeGC(display, imageGC); imageGC = 0; } } void setXClip(MultiRectArea mra, long gc) { if (mra == null) { resetXClip(gc); } else { int nRects = mra.getRectCount(); X11.XRectangle xrects = createXRects(mra.rect); x11.XSetClipRectangles(display, gc, 0, 0, xrects, nRects, X11Defs.Unsorted); xrects.free(); } } void resetXClip(long gc) { x11.XSetClipMask(display, gc, X11Defs.None); } void setXftClip(MultiRectArea mra) { if (mra == null){ resetXftClip(); } else { X11.XRectangle clipXRects = createXRects(mra.rect); xft.XftDrawSetClipRectangles(xftDraw, 0, 0, clipXRects, mra.getRectCount()); clipXRects.free(); } } void resetXftClip() { xft.XftDrawSetClip(xftDraw, 0); } protected void setTransformedClip(MultiRectArea clip) { super.setTransformedClip(clip); if (xftDraw != 0) { setXftClip(clip); } if (gc != 0) { setXClip(clip, gc); } } void setGCFunction(int func) { x11.XSetFunction(display, gc, func); } void setImageGCFunction(int func) { // Note: works with imageGC x11.XSetFunction(display, imageGC, func); } Surface getSurface() { return dstSurf; } public void setStroke(Stroke s) { super.setStroke(s); if (s instanceof BasicStroke) { BasicStroke bs = (BasicStroke) s; if (bs.getMiterLimit() != 10.f) { // Check if it is same as in xlib nativeLines = false; return; } X11.XGCValues gcVals = x11.createXGCValues(true); gcVals.set_line_width(Math.round(bs.getLineWidth())); gcVals.set_join_style(bs.getLineJoin()); gcVals.set_cap_style(bs.getEndCap()+1); gcVals.set_dash_offset(Math.round(bs.getDashPhase())); int n = 0; if (bs.getDashArray() == null) { gcVals.set_line_style(X11Defs.LineSolid); gcVals.set_dashes((byte)1); } else { gcVals.set_line_style(X11Defs.LineOnOffDash); n = bs.getDashArray().length; if (n == 1) { gcVals.set_dashes((byte)Math.round(bs.getDashArray()[0])); } else { long dashList = Utils.memaccess.malloc(n); float[] dashArray = bs.getDashArray(); for (int i = 0; i < n; i++) { Utils.memaccess.setByte(dashList+i, (byte) Math.round(dashArray[i])); } x11.XSetDashes( display, gc, Math.round(bs.getDashPhase()), dashList, bs.getDashArray().length ); Utils.memaccess.free(dashList); } } x11.XChangeGC( display, gc, X11Defs.GCLineWidth | X11Defs.GCJoinStyle | X11Defs.GCCapStyle | X11Defs.GCDashOffset | X11Defs.GCLineStyle | (n==1 ? X11Defs.GCDashList : 0), gcVals ); gcVals.free(); nativeLines = true; } else { nativeLines = false; } } public void setTransform(AffineTransform transform) { super.setTransform(transform); if ((transform.getType() & AffineTransform.TYPE_MASK_SCALE) != 0) { scalingTransform = true; } else { scalingTransform = false; } } public void drawLine(int x1, int y1, int x2, int y2) { if ( nativeLines && nativePaint && !scalingTransform && !transparentColor && simpleComposite ) { float points[] = new float[]{x1, y1, x2, y2}; transform.transform(points, 0, points, 0, 2); x11.XDrawLine( display, drawable, gc, (int) points[0], (int) points[1], (int) points[2], (int) points[3] ); } else { super.drawLine(x1, y1, x2, y2); } } public void drawPolygon(int[] xpoints, int[] ypoints, int npoints) { if ( nativeLines && nativePaint && !scalingTransform && !transparentColor && simpleComposite ) { float points[] = new float[npoints<<1]; int i; for (i = 0; i < npoints; i++) { points[i<<1] = xpoints[i]; points[(i<<1) + 1] = ypoints[i]; } transform.transform(points, 0, points, 0, npoints); // Create XPoint's long xPoints = Utils.memaccess.malloc((npoints+1) << 2); // sizeof XPoint = 4 long ptr = xPoints; for (i = 0; i < npoints; i++) { Utils.memaccess.setShort(ptr, (short) points[i<<1]); Utils.memaccess.setShort(ptr+2, (short) points[(i<<1)+1]); ptr += 4; // sizeof XPoint = 4 } // Add first point again to close path Utils.memaccess.setShort(ptr, (short) points[0]); Utils.memaccess.setShort(ptr+2, (short) points[1]); x11.XDrawLines( display, drawable, gc, xPoints, npoints+1, X11Defs.CoordModeOrigin ); Utils.memaccess.free(xPoints); } else { super.drawPolygon(xpoints, ypoints, npoints); } } public void drawPolygon(Polygon polygon) { drawPolygon(polygon.xpoints, polygon.ypoints, polygon.npoints); } public void drawPolyline(int[] xpoints, int[] ypoints, int npoints) { if ( nativeLines && nativePaint && !scalingTransform && !transparentColor && simpleComposite ) { float points[] = new float[npoints<<1]; for (int i = 0; i < npoints; i++) { points[i<<1] = xpoints[i]; points[(i<<1) + 1] = ypoints[i]; } transform.transform(points, 0, points, 0, npoints); // Create XPoint's long xPoints = Utils.memaccess.malloc((npoints) << 2); // sizeof XPoint = 4 long ptr = xPoints; for (int i = 0; i < npoints; i++) { Utils.memaccess.setShort(ptr, (short) points[i<<1]); Utils.memaccess.setShort(ptr+2, (short) points[(i<<1)+1]); ptr += 4; // sizeof XPoint = 4 } x11.XDrawLines( display, drawable, gc, xPoints, npoints, X11Defs.CoordModeOrigin ); Utils.memaccess.free(xPoints); } else { super.drawPolyline(xpoints, ypoints, npoints); } } public void drawRect(int x, int y, int width, int height) { if ( nativeLines && nativePaint && !transparentColor && simpleComposite && (transform.getType() & AffineTransform.TYPE_TRANSLATION) != 0 ) { Point2D rectOrig = new Point2D.Float(x, y); transform.transform(rectOrig, rectOrig); x11.XDrawRectangle( display, drawable, gc, (int) rectOrig.getX(), (int) rectOrig.getY(), width, height ); } else { super.drawRect(x, y, width, height); } } public void drawArc(int x, int y, int width, int height, int sa, int ea) { if ( nativeLines && nativePaint && !transparentColor && simpleComposite && (transform.getType() & AffineTransform.TYPE_TRANSLATION) != 0 ) { Point2D orig = new Point2D.Float(x, y); transform.transform(orig, orig); x11.XDrawArc( display, drawable, gc, (int) orig.getX(), (int) orig.getY(), width, height, sa << 6, ea << 6 ); } else { super.drawArc(x, y, width, height, sa, ea); } } public void drawOval(int x, int y, int width, int height) { drawArc(x, y, width, height, 0, 360); } public void setComposite(Composite composite) { super.setComposite(composite); if (composite instanceof AlphaComposite) { AlphaComposite acomp = (AlphaComposite) composite; if (acomp.getRule() == AlphaComposite.SRC) { simpleComposite = true; } else if (acomp.getAlpha() != 1.0f) { simpleComposite = false; } else { simpleComposite = true; } } else { simpleComposite = false; } } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.test.api.event; import org.flowable.engine.common.api.FlowableException; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.api.delegate.event.FlowableEventDispatcher; import org.flowable.engine.delegate.event.BaseEntityEventListener; import org.flowable.engine.delegate.event.FlowableEngineEventType; import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl; import org.flowable.engine.delegate.event.impl.FlowableEventDispatcherImpl; import org.flowable.engine.delegate.event.impl.FlowableEventImpl; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl; import org.flowable.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.task.Task; /** * * @author Frederik Heremans */ public abstract class FlowableEventDispatcherTest extends PluggableFlowableTestCase { protected FlowableEventDispatcher dispatcher; @Override protected void setUp() throws Exception { super.setUp(); dispatcher = new FlowableEventDispatcherImpl(); } /** * Test adding a listener and check if events are sent to it. Also checks that after removal, no events are received. */ public void addAndRemoveEventListenerAllEvents() throws Exception { // Create a listener that just adds the events to a list TestFlowableEventListener newListener = new TestFlowableEventListener(); // Add event-listener to dispatcher dispatcher.addEventListener(newListener); FlowableEntityEventImpl event1 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_CREATED); FlowableEntityEventImpl event2 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_CREATED); // Dispatch events dispatcher.dispatchEvent(event1); dispatcher.dispatchEvent(event2); assertEquals(2, newListener.getEventsReceived().size()); assertEquals(event1, newListener.getEventsReceived().get(0)); assertEquals(event2, newListener.getEventsReceived().get(1)); // Remove listener and dispatch events again, listener should not be // invoked dispatcher.removeEventListener(newListener); newListener.clearEventsReceived(); dispatcher.dispatchEvent(event1); dispatcher.dispatchEvent(event2); assertTrue(newListener.getEventsReceived().isEmpty()); } /** * Test adding a listener and check if events are sent to it, for the types it was registered for. Also checks that after removal, no events are received. */ public void addAndRemoveEventListenerTyped() throws Exception { // Create a listener that just adds the events to a list TestFlowableEventListener newListener = new TestFlowableEventListener(); // Add event-listener to dispatcher dispatcher.addEventListener(newListener, FlowableEngineEventType.ENTITY_CREATED, FlowableEngineEventType.ENTITY_DELETED); FlowableEntityEventImpl event1 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_CREATED); FlowableEntityEventImpl event2 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_DELETED); FlowableEntityEventImpl event3 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_UPDATED); // Dispatch events, only 2 out of 3 should have entered the listener dispatcher.dispatchEvent(event1); dispatcher.dispatchEvent(event2); dispatcher.dispatchEvent(event3); assertEquals(2, newListener.getEventsReceived().size()); assertEquals(event1, newListener.getEventsReceived().get(0)); assertEquals(event2, newListener.getEventsReceived().get(1)); // Remove listener and dispatch events again, listener should not be // invoked dispatcher.removeEventListener(newListener); newListener.clearEventsReceived(); dispatcher.dispatchEvent(event1); dispatcher.dispatchEvent(event2); assertTrue(newListener.getEventsReceived().isEmpty()); } /** * Test that adding a listener with a null-type is never called. */ public void addAndRemoveEventListenerTypedNullType() throws Exception { // Create a listener that just adds the events to a list TestFlowableEventListener newListener = new TestFlowableEventListener(); // Add event-listener to dispatcher dispatcher.addEventListener(newListener, (FlowableEngineEventType) null); FlowableEntityEventImpl event1 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_CREATED); FlowableEntityEventImpl event2 = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_DELETED); // Dispatch events, all should have entered the listener dispatcher.dispatchEvent(event1); dispatcher.dispatchEvent(event2); assertTrue(newListener.getEventsReceived().isEmpty()); } /** * Test the {@link BaseEntityEventListener} shipped with Flowable. */ public void baseEntityEventListener() throws Exception { TestBaseEntityEventListener listener = new TestBaseEntityEventListener(); dispatcher.addEventListener(listener); FlowableEntityEventImpl createEvent = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_CREATED); FlowableEntityEventImpl deleteEvent = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_DELETED); FlowableEntityEventImpl updateEvent = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.ENTITY_UPDATED); FlowableEntityEventImpl otherEvent = new FlowableEntityEventImpl(processEngineConfiguration.getTaskEntityManager().create(), FlowableEngineEventType.CUSTOM); // Dispatch create event dispatcher.dispatchEvent(createEvent); assertTrue(listener.isCreateReceived()); assertFalse(listener.isUpdateReceived()); assertFalse(listener.isCustomReceived()); assertFalse(listener.isInitializeReceived()); assertFalse(listener.isDeleteReceived()); listener.reset(); // Dispatch update event dispatcher.dispatchEvent(updateEvent); assertTrue(listener.isUpdateReceived()); assertFalse(listener.isCreateReceived()); assertFalse(listener.isCustomReceived()); assertFalse(listener.isDeleteReceived()); listener.reset(); // Dispatch delete event dispatcher.dispatchEvent(deleteEvent); assertTrue(listener.isDeleteReceived()); assertFalse(listener.isCreateReceived()); assertFalse(listener.isCustomReceived()); assertFalse(listener.isUpdateReceived()); listener.reset(); // Dispatch other event dispatcher.dispatchEvent(otherEvent); assertTrue(listener.isCustomReceived()); assertFalse(listener.isCreateReceived()); assertFalse(listener.isUpdateReceived()); assertFalse(listener.isDeleteReceived()); listener.reset(); // Test typed entity-listener listener = new TestBaseEntityEventListener(Task.class); // Dispatch event for a task, should be received dispatcher.addEventListener(listener); dispatcher.dispatchEvent(createEvent); assertTrue(listener.isCreateReceived()); listener.reset(); // Dispatch event for a execution, should NOT be received FlowableEntityEventImpl createEventForExecution = new FlowableEntityEventImpl(new ExecutionEntityImpl(), FlowableEngineEventType.ENTITY_CREATED); dispatcher.dispatchEvent(createEventForExecution); assertFalse(listener.isCreateReceived()); } /** * Test dispatching behavior when an exception occurs in the listener */ public void exceptionInListener() throws Exception { // Create listener that doesn't force the dispatching to fail TestExceptionFlowableEventListener listener = new TestExceptionFlowableEventListener(false); TestFlowableEventListener secondListener = new TestFlowableEventListener(); dispatcher.addEventListener(listener); dispatcher.addEventListener(secondListener); FlowableEventImpl event = new FlowableEventImpl(FlowableEngineEventType.ENTITY_CREATED); try { dispatcher.dispatchEvent(event); assertEquals(1, secondListener.getEventsReceived().size()); } catch (Throwable t) { fail("No exception expected"); } // Remove listeners dispatcher.removeEventListener(listener); dispatcher.removeEventListener(secondListener); // Create listener that forces the dispatching to fail listener = new TestExceptionFlowableEventListener(true); secondListener = new TestFlowableEventListener(); dispatcher.addEventListener(listener); dispatcher.addEventListener(secondListener); try { dispatcher.dispatchEvent(event); fail("Exception expected"); } catch (Throwable t) { assertTrue(t instanceof FlowableException); assertTrue(t.getCause() instanceof RuntimeException); assertEquals("Test exception", t.getCause().getMessage()); // Second listener should NOT have been called assertEquals(0, secondListener.getEventsReceived().size()); } } /** * Test conversion of string-value (and list) in list of {@link FlowableEngineEventType}s, used in configuration of process-engine * {@link ProcessEngineConfigurationImpl#setTypedEventListeners(java.util.Map)} . */ public void activitiEventTypeParsing() throws Exception { // Check with empty null FlowableEngineEventType[] types = FlowableEngineEventType.getTypesFromString(null); assertNotNull(types); assertEquals(0, types.length); // Check with empty string types = FlowableEngineEventType.getTypesFromString(""); assertNotNull(types); assertEquals(0, types.length); // Single value types = FlowableEngineEventType.getTypesFromString("ENTITY_CREATED"); assertNotNull(types); assertEquals(1, types.length); assertEquals(FlowableEngineEventType.ENTITY_CREATED, types[0]); // Multiple value types = FlowableEngineEventType.getTypesFromString("ENTITY_CREATED,ENTITY_DELETED"); assertNotNull(types); assertEquals(2, types.length); assertEquals(FlowableEngineEventType.ENTITY_CREATED, types[0]); assertEquals(FlowableEngineEventType.ENTITY_DELETED, types[1]); // Additional separators should be ignored types = FlowableEngineEventType.getTypesFromString(",ENTITY_CREATED,,ENTITY_DELETED,,,"); assertNotNull(types); assertEquals(2, types.length); assertEquals(FlowableEngineEventType.ENTITY_CREATED, types[0]); assertEquals(FlowableEngineEventType.ENTITY_DELETED, types[1]); // Invalid type name try { FlowableEngineEventType.getTypesFromString("WHOOPS,ENTITY_DELETED"); fail("Exception expected"); } catch (FlowableIllegalArgumentException expected) { // Expected exception assertEquals("Invalid event-type: WHOOPS", expected.getMessage()); } } }
package it.internal.org.springframework.content.rest.controllers; import java.io.ByteArrayInputStream; import java.util.Date; import java.util.UUID; import com.github.paulcwarren.ginkgo4j.Ginkgo4jConfiguration; import com.github.paulcwarren.ginkgo4j.Ginkgo4jSpringRunner; import internal.org.springframework.content.rest.support.StoreConfig; import internal.org.springframework.content.rest.support.TestStore; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.content.rest.config.RestConfiguration; import org.springframework.core.io.Resource; import org.springframework.core.io.WritableResource; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.BeforeEach; import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.Context; import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.Describe; import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.FIt; import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.It; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(Ginkgo4jSpringRunner.class) @Ginkgo4jConfiguration(threads = 1) @WebAppConfiguration @ContextConfiguration(classes = { StoreConfig.class, DelegatingWebMvcConfiguration.class, RepositoryRestMvcConfiguration.class, RestConfiguration.class }) @Transactional @ActiveProfiles("store") public class StoreRestEndpointsIT { @Autowired TestStore store; @Autowired private WebApplicationContext context; private MockMvc mvc; private String path; private String request; private LastModifiedDate lastModifiedDate; { Describe("Store Rest Endpoints", () -> { BeforeEach(() -> { mvc = MockMvcBuilders.webAppContextSetup(context).build(); }); Context("given a root resource path", () -> { BeforeEach(() -> { path = "/" + UUID.randomUUID() + ".txt"; request = "/teststore" + path; }); Context("given a GET request to that path", () -> { It("should return 404", () -> { mvc.perform(get(request)).andExpect(status().isNotFound()); }); }); Context("given a POST to that path with content", () -> { It("should set the content and return 201", () -> { String content = "New multi-part content"; mvc.perform(fileUpload(request).file(new MockMultipartFile("file", "test-file.txt", "text/plain", content.getBytes()))) .andExpect(status().isCreated()); Resource r = store.getResource(path); assertThat(IOUtils.contentEquals( new ByteArrayInputStream("New multi-part content".getBytes()), r.getInputStream()), is(true)); }); }); Context("given a DELETE request to that path", () -> { It("should return a 404", () -> { mvc.perform(delete(request)).andExpect(status().isNotFound()); }); }); }); Context("given a root resource", () -> { BeforeEach(() -> { path = "/" + UUID.randomUUID() + ".txt"; request = "/teststore" + path; Resource r = store.getResource(path); if (r instanceof WritableResource) { IOUtils.copy( new ByteArrayInputStream("Existing content".getBytes()), ((WritableResource) r).getOutputStream()); } lastModifiedDate.setMvc(mvc); lastModifiedDate.setUrl("/teststore" + path); lastModifiedDate.setLastModifiedDate(new Date(r.lastModified())); lastModifiedDate.setContent("Existing content"); }); It("should return the resource's content", () -> { MockHttpServletResponse response = mvc.perform(get(request)) .andExpect(status().isOk()).andReturn().getResponse(); assertThat(response, is(not(nullValue()))); assertThat(response.getContentAsString(), is("Existing content")); }); It("should return a byte range when requested", () -> { MockHttpServletResponse response = mvc .perform(get(request).header("range", "bytes=9-12")) .andExpect(status().isPartialContent()).andReturn() .getResponse(); assertThat(response, is(not(nullValue()))); assertThat(response.getContentAsString(), is("cont")); }); It("should overwrite the resource's content", () -> { mvc.perform(put(request).content("New Existing content") .contentType("text/plain")).andExpect(status().isOk()); Resource r = store.getResource(path); assertThat(IOUtils.contentEquals( new ByteArrayInputStream("New Existing content".getBytes()), r.getInputStream()), is(true)); }); Context("a POST to /{store}/{path} with multi-part form-data ", () -> { It("should overwrite the content and return 200", () -> { String content = "New multi-part content"; mvc.perform(fileUpload(request).file(new MockMultipartFile("file", "tests-file.txt", "text/plain", content.getBytes()))) .andExpect(status().isOk()); Resource r = store.getResource(path); assertThat(IOUtils.contentEquals( new ByteArrayInputStream( "New multi-part content".getBytes()), r.getInputStream()), is(true)); }); }); It("should delete the resource", () -> { mvc.perform(delete(request)).andExpect(status().isNoContent()); Resource r = store.getResource(path); assertThat(r.exists(), is(false)); }); lastModifiedDate = new LastModifiedDate(); }); Context("given a nested resource", () -> { BeforeEach(() -> { path = "/a/b/" + UUID.randomUUID() + ".txt"; request = "/teststore" + path; Resource r = store.getResource(path); if (r instanceof WritableResource) { IOUtils.copy( new ByteArrayInputStream("Existing content".getBytes()), ((WritableResource) r).getOutputStream()); } }); It("should return the resource's content", () -> { MockHttpServletResponse response = mvc.perform(get(request)) .andExpect(status().isOk()).andReturn().getResponse(); assertThat(response, is(not(nullValue()))); assertThat(response.getContentAsString(), is("Existing content")); }); It("should return a byte range when requested", () -> { MockHttpServletResponse response = mvc .perform(get(request).header("range", "bytes=9-12")) .andExpect(status().isPartialContent()).andReturn() .getResponse(); assertThat(response, is(not(nullValue()))); assertThat(response.getContentAsString(), is("cont")); }); Context("given a typical browser request", () -> { It("should return the resource's content", () -> { MockHttpServletResponse response = mvc .perform(get(request).accept(new String[] { "text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "image/apng", "*/*;q=0.8" })) .andExpect(status().isOk()).andReturn().getResponse(); assertThat(response, is(not(nullValue()))); assertThat(response.getContentAsString(), is("Existing content")); }); }); It("should overwrite the resource's content", () -> { mvc.perform(put(request).content("New Existing content") .contentType("text/plain")).andExpect(status().isOk()); Resource r = store.getResource(path); assertThat(IOUtils.contentEquals( new ByteArrayInputStream("New Existing content".getBytes()), r.getInputStream()), is(true)); }); Context("a POST to /{store}/{path} with multi-part form-data ", () -> { It("should overwrite the content and return 200", () -> { String content = "New multi-part content"; mvc.perform(fileUpload(request).file(new MockMultipartFile("file", "tests-file.txt", "text/plain", content.getBytes()))) .andExpect(status().isOk()); Resource r = store.getResource(path); assertThat(IOUtils.contentEquals( new ByteArrayInputStream( "New multi-part content".getBytes()), r.getInputStream()), is(true)); }); }); It("should delete the resource", () -> { mvc.perform(delete(request)).andExpect(status().isNoContent()); Resource r = store.getResource(path); assertThat(r.exists(), is(false)); }); }); }); } @Test public void noop() { } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysml.test.integration.functions.frame; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.DataFrame; import org.apache.spark.sql.Row; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.types.StructType; import org.apache.sysml.api.DMLScript; import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM; import org.apache.sysml.parser.Expression.ValueType; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.controlprogram.context.ExecutionContextFactory; import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext; import org.apache.sysml.runtime.instructions.spark.functions.CopyFrameBlockPairFunction; import org.apache.sysml.runtime.instructions.spark.utils.FrameRDDConverterUtils; import org.apache.sysml.runtime.instructions.spark.utils.FrameRDDConverterUtils.LongFrameToLongWritableFrameFunction; import org.apache.sysml.runtime.instructions.spark.utils.FrameRDDConverterUtils.LongWritableFrameToLongFrameFunction; import org.apache.sysml.runtime.io.FrameReader; import org.apache.sysml.runtime.io.FrameReaderFactory; import org.apache.sysml.runtime.io.FrameWriter; import org.apache.sysml.runtime.io.FrameWriterFactory; import org.apache.sysml.runtime.io.MatrixReader; import org.apache.sysml.runtime.io.MatrixReaderFactory; import org.apache.sysml.runtime.io.MatrixWriter; import org.apache.sysml.runtime.io.MatrixWriterFactory; import org.apache.sysml.runtime.matrix.MatrixCharacteristics; import org.apache.sysml.runtime.matrix.data.CSVFileFormatProperties; import org.apache.sysml.runtime.matrix.data.FrameBlock; import org.apache.sysml.runtime.matrix.data.InputInfo; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.matrix.data.MatrixIndexes; import org.apache.sysml.runtime.matrix.data.OutputInfo; import org.apache.sysml.runtime.util.MapReduceTool; import org.apache.sysml.runtime.util.UtilFunctions; import org.apache.sysml.test.integration.AutomatedTestBase; import org.apache.sysml.test.integration.TestConfiguration; import org.apache.sysml.test.utils.TestUtils; import org.junit.Assert; import org.junit.Test; public class FrameConverterTest extends AutomatedTestBase { private final static String TEST_DIR = "functions/frame/"; private final static String TEST_NAME = "FrameConv"; private final static String TEST_CLASS_DIR = TEST_DIR + FrameConverterTest.class.getSimpleName() + "/"; private final static int rows = 1593; private final static ValueType[] schemaStrings = new ValueType[]{ValueType.STRING, ValueType.STRING, ValueType.STRING}; private final static ValueType[] schemaMixed = new ValueType[]{ValueType.STRING, ValueType.DOUBLE, ValueType.INT, ValueType.BOOLEAN}; private final static List<ValueType> schemaMixedLargeListStr = Collections.nCopies(600, ValueType.STRING); private final static List<ValueType> schemaMixedLargeListDble = Collections.nCopies(600, ValueType.DOUBLE); private final static List<ValueType> schemaMixedLargeListInt = Collections.nCopies(600, ValueType.INT); private final static List<ValueType> schemaMixedLargeListBool = Collections.nCopies(600, ValueType.BOOLEAN); private static List<ValueType> schemaMixedLargeList = null; static { schemaMixedLargeList = new ArrayList<ValueType>(schemaMixedLargeListStr); schemaMixedLargeList.addAll(schemaMixedLargeListDble); schemaMixedLargeList.addAll(schemaMixedLargeListInt); schemaMixedLargeList.addAll(schemaMixedLargeListBool); } private static ValueType[] schemaMixedLarge = new ValueType[schemaMixedLargeList.size()]; static { schemaMixedLarge = (ValueType[]) schemaMixedLargeList.toArray(schemaMixedLarge); } private enum ConvType { CSV2BIN, BIN2CSV, TXTCELL2BIN, BIN2TXTCELL, MAT2BIN, BIN2MAT, DFRM2BIN, BIN2DFRM, } private static String separator = ","; @Override public void setUp() { TestUtils.clearAssertionInformation(); addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {"B"})); } @Test public void testFrameStringsCsvBinSpark() { runFrameConverterTest(schemaStrings, ConvType.CSV2BIN); } @Test public void testFrameMixedCsvBinSpark() { runFrameConverterTest(schemaMixed, ConvType.CSV2BIN); } @Test public void testFrameStringsBinCsvSpark() { runFrameConverterTest(schemaStrings, ConvType.BIN2CSV); } @Test public void testFrameMixedBinCsvSpark() { runFrameConverterTest(schemaMixed, ConvType.BIN2CSV); } @Test public void testFrameStringsTxtCellBinSpark() { runFrameConverterTest(schemaStrings, ConvType.TXTCELL2BIN); } @Test public void testFrameMixedTxtCellBinSpark() { runFrameConverterTest(schemaMixed, ConvType.TXTCELL2BIN); } @Test public void testFrameStringsBinTxtCellSpark() { runFrameConverterTest(schemaStrings, ConvType.BIN2TXTCELL); } @Test public void testFrameMixedBinTxtCellSpark() { runFrameConverterTest(schemaMixed, ConvType.BIN2TXTCELL); } @Test public void testFrameStringsMatrixBinSpark() { runFrameConverterTest(schemaStrings, ConvType.MAT2BIN); } @Test public void testFrameMixedMatrixBinSpark() { runFrameConverterTest(schemaMixed, ConvType.MAT2BIN); } @Test public void testFrameStringsBinMatrixSpark() { runFrameConverterTest(schemaStrings, ConvType.BIN2MAT); } @Test public void testFrameMixedBinMatrixSpark() { runFrameConverterTest(schemaMixed, ConvType.BIN2MAT); } @Test public void testFrameMixedMultiColBlkMatrixBinSpark() { runFrameConverterTest(schemaMixedLarge, ConvType.MAT2BIN); } @Test public void testFrameMixedMultiColBlkBinMatrixSpark() { runFrameConverterTest(schemaMixedLarge, ConvType.BIN2MAT); } @Test public void testFrameMixedDFrameBinSpark() { runFrameConverterTest(schemaMixedLarge, ConvType.DFRM2BIN); } @Test public void testFrameMixedBinDFrameSpark() { runFrameConverterTest(schemaMixedLarge, ConvType.BIN2DFRM); } /** * * @param schema * @param type * @param instType */ private void runFrameConverterTest( ValueType[] schema, ConvType type) { RUNTIME_PLATFORM platformOld = rtplatform; DMLScript.rtplatform = RUNTIME_PLATFORM.SPARK; boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG; DMLScript.USE_LOCAL_SPARK_CONFIG = true; try { TestConfiguration config = getTestConfiguration(TEST_NAME); loadTestConfiguration(config); //data generation double[][] A = getRandomMatrix(rows, schema.length, -10, 10, 0.9, 2373); //prepare input/output infos OutputInfo oinfo = null; InputInfo iinfo = null; switch( type ) { case CSV2BIN: case DFRM2BIN: oinfo = OutputInfo.CSVOutputInfo; iinfo = InputInfo.BinaryBlockInputInfo; break; case BIN2CSV: oinfo = OutputInfo.BinaryBlockOutputInfo; iinfo = InputInfo.CSVInputInfo; break; case TXTCELL2BIN: oinfo = OutputInfo.TextCellOutputInfo; iinfo = InputInfo.BinaryBlockInputInfo; break; case BIN2TXTCELL: oinfo = OutputInfo.BinaryBlockOutputInfo; iinfo = InputInfo.TextCellInputInfo; break; case MAT2BIN: case BIN2DFRM: oinfo = OutputInfo.BinaryBlockOutputInfo; iinfo = InputInfo.BinaryBlockInputInfo; break; case BIN2MAT: oinfo = OutputInfo.BinaryBlockOutputInfo; iinfo = InputInfo.BinaryBlockInputInfo; break; default: throw new RuntimeException("Unsuported converter type: "+type.toString()); } if(type == ConvType.MAT2BIN || type == ConvType.BIN2MAT) runMatrixConverterAndVerify(schema, A, type, iinfo, oinfo); else runConverterAndVerify(schema, A, type, iinfo, oinfo); } catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { DMLScript.rtplatform = platformOld; DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld; } } /** * * @param schema * @param A * @param type * @param iinfo * @param oinfo * @param instType */ private void runConverterAndVerify( ValueType[] schema, double[][] A, ConvType type, InputInfo iinfo, OutputInfo oinfo ) throws IOException { try { //initialize the frame data. FrameBlock frame1 = new FrameBlock(schema); initFrameData(frame1, A, schema); //write frame data to hdfs FrameWriter writer = FrameWriterFactory.createFrameWriter(oinfo); writer.writeFrameToHDFS(frame1, input("A"), rows, schema.length); //run converter under test MatrixCharacteristics mc = new MatrixCharacteristics(rows, schema.length, -1, -1, -1); runConverter(type, mc, null, Arrays.asList(schema), input("A"), output("B")); //read frame data from hdfs FrameReader reader = FrameReaderFactory.createFrameReader(iinfo); FrameBlock frame2 = reader.readFrameFromHDFS(output("B"), rows, schema.length); //verify input and output frame verifyFrameData(frame1, frame2); } catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { MapReduceTool.deleteFileIfExistOnHDFS(input("A")); MapReduceTool.deleteFileIfExistOnHDFS(output("B")); } } /** * * @param schema * @param A * @param type * @param iinfo * @param oinfo * @param instType */ private void runMatrixConverterAndVerify( ValueType[] schema, double[][] A, ConvType type, InputInfo iinfo, OutputInfo oinfo ) throws IOException { try { MatrixCharacteristics mcMatrix = new MatrixCharacteristics(rows, schema.length, 1000, 1000, 0); MatrixCharacteristics mcFrame = new MatrixCharacteristics(rows, schema.length, -1, -1, -1); MatrixBlock matrixBlock1 = null; FrameBlock frame1 = null; if(type == ConvType.MAT2BIN) { //initialize the matrix (dense) data. matrixBlock1 = new MatrixBlock(rows, schema.length, false); matrixBlock1.init(A, rows, schema.length); //write matrix data to hdfs MatrixWriter matWriter = MatrixWriterFactory.createMatrixWriter(oinfo); matWriter.writeMatrixToHDFS(matrixBlock1, input("A"), rows, schema.length, mcMatrix.getRowsPerBlock(), mcMatrix.getColsPerBlock(), mcMatrix.getNonZeros()); } else { //initialize the frame data. frame1 = new FrameBlock(schema); initFrameData(frame1, A, schema); //write frame data to hdfs FrameWriter writer = FrameWriterFactory.createFrameWriter(oinfo); writer.writeFrameToHDFS(frame1, input("A"), rows, schema.length); } //run converter under test runConverter(type, mcFrame, mcMatrix, Arrays.asList(schema), input("A"), output("B")); if(type == ConvType.MAT2BIN) { //read frame data from hdfs FrameReader reader = FrameReaderFactory.createFrameReader(iinfo); FrameBlock frame2 = reader.readFrameFromHDFS(output("B"), rows, schema.length); //verify input and output frame/matrix verifyFrameMatrixData(frame2, matrixBlock1); } else { //read matrix data from hdfs MatrixReader matReader = MatrixReaderFactory.createMatrixReader(iinfo); MatrixBlock matrixBlock2 = matReader.readMatrixFromHDFS(output("B"), rows, schema.length, mcMatrix.getRowsPerBlock(), mcMatrix.getColsPerBlock(), mcMatrix.getNonZeros()); //verify input and output frame/matrix verifyFrameMatrixData(frame1, matrixBlock2); } } catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { MapReduceTool.deleteFileIfExistOnHDFS(input("A")); MapReduceTool.deleteFileIfExistOnHDFS(output("B")); } } /** * * @param frame * @param data * @param lschema */ private void initFrameData(FrameBlock frame, double[][] data, ValueType[] lschema) { Object[] row1 = new Object[lschema.length]; for( int i=0; i<rows; i++ ) { for( int j=0; j<lschema.length; j++ ) data[i][j] = UtilFunctions.objectToDouble(lschema[j], row1[j] = UtilFunctions.doubleToObject(lschema[j], data[i][j])); frame.appendRow(row1); } } /** * * @param frame1 * @param frame2 */ private void verifyFrameData(FrameBlock frame1, FrameBlock frame2) { for ( int i=0; i<frame1.getNumRows(); i++ ) for( int j=0; j<frame1.getNumColumns(); j++ ) { String val1 = UtilFunctions.objectToString(frame1.get(i, j)); String val2 = UtilFunctions.objectToString(frame2.get(i, j)); if( UtilFunctions.compareTo(ValueType.STRING, val1, val2) != 0) Assert.fail("The original data for cell ("+ i + "," + j + ") is " + val1 + ", not same as the converted value " + val2); } } /** * * @param frame1 * @param frame2 */ private void verifyFrameMatrixData(FrameBlock frame, MatrixBlock matrix) { for ( int i=0; i<frame.getNumRows(); i++ ) for( int j=0; j<frame.getNumColumns(); j++ ) { Object val1 = UtilFunctions.doubleToObject(frame.getSchema()[j], UtilFunctions.objectToDouble(frame.getSchema()[j], frame.get(i, j))); Object val2 = UtilFunctions.doubleToObject(frame.getSchema()[j], matrix.getValue(i, j)); if(( UtilFunctions.compareTo(frame.getSchema()[j], val1, val2)) != 0) Assert.fail("Frame value for cell ("+ i + "," + j + ") is " + val1 + ", is not same as matrix value " + val2); } } /** * @param oinfo * @param frame1 * @param frame2 * @param fprop * @param schema * @return * @throws DMLRuntimeException, IOException */ @SuppressWarnings("unchecked") private void runConverter(ConvType type, MatrixCharacteristics mc, MatrixCharacteristics mcMatrix, List<ValueType> schema, String fnameIn, String fnameOut) throws DMLRuntimeException, IOException { SparkExecutionContext sec = (SparkExecutionContext) ExecutionContextFactory.createContext(); JavaSparkContext sc = sec.getSparkContext(); ValueType[] lschema = schema.toArray(new ValueType[0]); MapReduceTool.deleteFileIfExistOnHDFS(fnameOut); switch( type ) { case CSV2BIN: { InputInfo iinfo = InputInfo.CSVInputInfo; OutputInfo oinfo = OutputInfo.BinaryBlockOutputInfo; JavaPairRDD<LongWritable,Text> rddIn = sc.hadoopFile(fnameIn, iinfo.inputFormatClass, iinfo.inputKeyClass, iinfo.inputValueClass); JavaPairRDD<LongWritable, FrameBlock> rddOut = FrameRDDConverterUtils .csvToBinaryBlock(sc, rddIn, mc, null, false, separator, false, 0) .mapToPair(new LongFrameToLongWritableFrameFunction()); rddOut.saveAsHadoopFile(fnameOut, LongWritable.class, FrameBlock.class, oinfo.outputFormatClass); break; } case BIN2CSV: { InputInfo iinfo = InputInfo.BinaryBlockInputInfo; JavaPairRDD<LongWritable, FrameBlock> rddIn = sc.hadoopFile(fnameIn, iinfo.inputFormatClass, LongWritable.class, FrameBlock.class); JavaPairRDD<Long, FrameBlock> rddIn2 = rddIn.mapToPair(new CopyFrameBlockPairFunction(false)); CSVFileFormatProperties fprop = new CSVFileFormatProperties(); JavaRDD<String> rddOut = FrameRDDConverterUtils.binaryBlockToCsv(rddIn2, mc, fprop, true); rddOut.saveAsTextFile(fnameOut); break; } case TXTCELL2BIN: { InputInfo iinfo = InputInfo.TextCellInputInfo; OutputInfo oinfo = OutputInfo.BinaryBlockOutputInfo; JavaPairRDD<LongWritable,Text> rddIn = sc.hadoopFile(fnameIn, iinfo.inputFormatClass, iinfo.inputKeyClass, iinfo.inputValueClass); JavaPairRDD<LongWritable, FrameBlock> rddOut = FrameRDDConverterUtils .textCellToBinaryBlock(sc, rddIn, mc, lschema) .mapToPair(new LongFrameToLongWritableFrameFunction()); rddOut.saveAsHadoopFile(fnameOut, LongWritable.class, FrameBlock.class, oinfo.outputFormatClass); break; } case BIN2TXTCELL: { InputInfo iinfo = InputInfo.BinaryBlockInputInfo; JavaPairRDD<LongWritable, FrameBlock> rddIn = sc.hadoopFile(fnameIn, iinfo.inputFormatClass, LongWritable.class, FrameBlock.class); JavaPairRDD<Long, FrameBlock> rddIn2 = rddIn.mapToPair(new CopyFrameBlockPairFunction(false)); JavaRDD<String> rddOut = FrameRDDConverterUtils.binaryBlockToTextCell(rddIn2, mc); rddOut.saveAsTextFile(fnameOut); break; } case MAT2BIN: { InputInfo iinfo = InputInfo.BinaryBlockInputInfo; OutputInfo oinfo = OutputInfo.BinaryBlockOutputInfo; JavaPairRDD<MatrixIndexes,MatrixBlock> rddIn = sc.hadoopFile(fnameIn, iinfo.inputFormatClass, iinfo.inputKeyClass, iinfo.inputValueClass); JavaPairRDD<LongWritable, FrameBlock> rddOut = FrameRDDConverterUtils.matrixBlockToBinaryBlock(sc, rddIn, mcMatrix); rddOut.saveAsHadoopFile(fnameOut, LongWritable.class, FrameBlock.class, oinfo.outputFormatClass); break; } case BIN2MAT: { InputInfo iinfo = InputInfo.BinaryBlockInputInfo; OutputInfo oinfo = OutputInfo.BinaryBlockOutputInfo; JavaPairRDD<Long, FrameBlock> rddIn = sc .hadoopFile(fnameIn, iinfo.inputFormatClass, LongWritable.class, FrameBlock.class) .mapToPair(new LongWritableFrameToLongFrameFunction()); JavaPairRDD<MatrixIndexes,MatrixBlock> rddOut = FrameRDDConverterUtils.binaryBlockToMatrixBlock(rddIn, mc, mcMatrix); rddOut.saveAsHadoopFile(fnameOut, MatrixIndexes.class, MatrixBlock.class, oinfo.outputFormatClass); break; } case DFRM2BIN: { OutputInfo oinfo = OutputInfo.BinaryBlockOutputInfo; //Create DataFrame SQLContext sqlContext = new SQLContext(sc); StructType dfSchema = FrameRDDConverterUtils.convertFrameSchemaToDFSchema(lschema, false); JavaRDD<Row> rowRDD = FrameRDDConverterUtils.csvToRowRDD(sc, fnameIn, separator, lschema); DataFrame df = sqlContext.createDataFrame(rowRDD, dfSchema); JavaPairRDD<LongWritable, FrameBlock> rddOut = FrameRDDConverterUtils .dataFrameToBinaryBlock(sc, df, mc, false/*, columns*/) .mapToPair(new LongFrameToLongWritableFrameFunction()); rddOut.saveAsHadoopFile(fnameOut, LongWritable.class, FrameBlock.class, oinfo.outputFormatClass); break; } case BIN2DFRM: { InputInfo iinfo = InputInfo.BinaryBlockInputInfo; OutputInfo oinfo = OutputInfo.BinaryBlockOutputInfo; JavaPairRDD<Long, FrameBlock> rddIn = sc .hadoopFile(fnameIn, iinfo.inputFormatClass, LongWritable.class, FrameBlock.class) .mapToPair(new LongWritableFrameToLongFrameFunction()); DataFrame df = FrameRDDConverterUtils.binaryBlockToDataFrame(new SQLContext(sc), rddIn, mc, lschema); //Convert back DataFrame to binary block for comparison using original binary to converted DF and back to binary JavaPairRDD<LongWritable, FrameBlock> rddOut = FrameRDDConverterUtils .dataFrameToBinaryBlock(sc, df, mc, true) .mapToPair(new LongFrameToLongWritableFrameFunction()); rddOut.saveAsHadoopFile(fnameOut, LongWritable.class, FrameBlock.class, oinfo.outputFormatClass); break; } default: throw new RuntimeException("Unsuported converter type: "+type.toString()); } sec.close(); } }
/* * Copyright (C) 2004 Felipe Gustavo de Almeida * Copyright (C) 2010-2014 The MPDroid Project * * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice,this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.a0z.mpd.exception; import org.a0z.mpd.Log; /** * Represents an MPD Server error with a stack trace, a detail message and elements from the * <A HREF="http://www.musicpd.org/doc/protocol/response_syntax.html">response syntax</A>. * * @author Felipe Gustavo de Almeida */ public class MPDException extends Exception { /** * The MPD protocol ACK error code given when there is an error with a given argument. */ public static final int ACK_ERROR_ARG = 2; /** * The MPD protocol ACK error code given when the argument target to a command was not expected * to exist, but does. */ public static final int ACK_ERROR_EXIST = 56; /** * The MPD protocol ACK error code given when sending command queue commands out of order. * This is no longer used in the standard implementation. */ public static final int ACK_ERROR_NOT_LIST = 1; /** * The MPD protocol ACK error code given when the argument target to a command was expected to\ * exist, but does not. */ public static final int ACK_ERROR_NO_EXIST = 50; /** * The MPD protocol ACK error code given when the password is incorrect. */ public static final int ACK_ERROR_PASSWORD = 3; /** * The MPD protocol ACK error code given when permission is denied for a command. */ public static final int ACK_ERROR_PERMISSION = 4; /** * The MPD protocol ACK error code given when player sync has failed. */ public static final int ACK_ERROR_PLAYER_SYNC = 55; /** * The MPD protocol ACK error code given when loading a playlist has failed. */ public static final int ACK_ERROR_PLAYLIST_LOAD = 53; /** * The MPD protocol ACK error code given when a playlist queue has reached it's maximum size. */ public static final int ACK_ERROR_PLAYLIST_MAX = 51; /** * The MPD protocol ACK error code given when a system error has occurred. */ public static final int ACK_ERROR_SYSTEM = 52; /** * The MPD protocol ACK error code given when an unknown error has occurred with the command. */ public static final int ACK_ERROR_UNKNOWN = 5; /** * The MPD protocol ACK error code given when attempting a media server database update when an * update is already taking place. */ public static final int ACK_ERROR_UPDATE_ALREADY = 54; /** * This occurs when there is a connection error or a non-standard error response from the media * server. */ private static final int ERROR_UNKNOWN = -1; private static final String TAG = "MPDException"; private static final long serialVersionUID = -5837769913914420046L; /** The command sent for this error. */ public final String mCommand; /** The position of the command queue the error occurred. 0 if not a command queue. */ public final int mCommandQueuePosition; /** The error code which caused this error in media server response. */ public final int mErrorCode; /** The message text which caused this error in media server response. */ public final String mErrorMessage; /** * Constructs a new {@code Exception} that includes the current stack trace. */ public MPDException() { mCommandQueuePosition = 0; mErrorCode = ERROR_UNKNOWN; mErrorMessage = "Exception thrown, no exception detail message given."; mCommand = null; } /** * Constructs a new {@code Exception} with the current stack trace, the specified detail * message and parses the media server error string for details given by fields in this * exception. * * @param detailMessage The detail message for this exception. */ public MPDException(final String detailMessage) { super(detailMessage); mErrorCode = getAckErrorCode(detailMessage); mCommandQueuePosition = getAckCommandQueuePosition(detailMessage); mCommand = parseString(detailMessage, '{', '}'); mErrorMessage = parseString(detailMessage, '}', '\0').trim(); } /** * Constructs a new {@code Exception} with the current stack trace, the specified detail * message, the specified cause and parses the media server error string for details given by * fields in this exception. * * @param detailMessage The detail message for this exception. * @param throwable The cause of this exception. */ public MPDException(final String detailMessage, final Throwable throwable) { super(detailMessage, throwable); mErrorCode = getAckErrorCode(detailMessage); mCommandQueuePosition = getAckCommandQueuePosition(detailMessage); mCommand = parseString(detailMessage, '{', '}'); mErrorMessage = parseString(detailMessage, '}', '\0').trim(); } /** * Constructs a new {@code Exception} with the current stack trace, the specified cause and * parses the media server error string for details given by fields in this exception. * * @param throwable The cause of this exception. */ public MPDException(final Throwable throwable) { super(throwable); final String detailMessage = throwable.getMessage(); mErrorCode = getAckErrorCode(detailMessage); mCommandQueuePosition = getAckCommandQueuePosition(detailMessage); mCommand = parseString(detailMessage, '{', '}'); mErrorMessage = parseString(detailMessage, '}', '\0').trim(); } /** * This method parses the MPD protocol formatted ACK detail message for the command queue * position where the error occurred. * * @param message The incoming media server ACK message. * @return The command queue position where the error occurred, -1 if the message is not * a valid media server ACK message. */ private static int getAckCommandQueuePosition(final String message) { final String parsed = parseString(message, '@', ']'); int queuePosition = -1; if (parsed != null) { try { queuePosition = Integer.parseInt(parsed); } catch (final NumberFormatException e) { Log.error(TAG, "Failed to parse ACK command queue position.", e); } } return queuePosition; } /** * This method parses the MPD protocol formatted ACK detail message for the MPD error code. * * @param message The incoming media server ACK message. * @return The MPD protocol error code, -1 if the message is not a valid media server ACK * message. */ public static int getAckErrorCode(final String message) { final String parsed = parseString(message, '[', '@'); int errorCode = ACK_ERROR_UNKNOWN; if (parsed != null) { try { errorCode = Integer.parseInt(parsed); } catch (final NumberFormatException e) { Log.error(TAG, "Failed to parse ACK error code.", e); } } return errorCode; } /** * This parses {@code message} in between the first found {@code start} parameter and {@code * end} parameter. In the index of {@code start} and {@code end} are equal, the index search * for the {@code end} parameter will begin after the {@code start} parameter index. If the * {@code start} parameter is null, the string will match the first character of the * {@code message}, if the {@code end} parameter is null, the string will match to the length * of * the String. This method is not intended to be an all-purpose string parser, and shouldn't be * used for anything beyond simple line parsing. * * @param message Message to parse. * @param start The first character to begin parsing. * @param end The final character to parse. * @return The substring of characters between the {@code start} and {@code end}, null if * parsing failed. */ private static String parseString(final String message, final char start, final char end) { String result = null; if (message != null) { final int startIndex; final int endIndex; if (start == '\0') { startIndex = 0; } else { startIndex = message.indexOf(start) + 1; } if (end == '\0') { endIndex = message.length(); } else { endIndex = message.indexOf(end, startIndex); } if (startIndex != -1 && endIndex != -1) { result = message.substring(startIndex, endIndex); } } return result; } /** * Checks this exception to see if it was a correctly parsed {@code ACK} message. * * @return True if this exception was caused by an {@code ACK} message, false otherwise. */ public boolean isACKError() { return mErrorCode == ERROR_UNKNOWN; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.planner.runtime.utils; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.table.functions.AggregateFunction; import org.apache.flink.table.functions.FunctionContext; import org.apache.flink.table.functions.FunctionLanguage; import org.apache.flink.table.functions.ScalarFunction; import java.util.Arrays; import java.util.Random; /** * Test scalar functions. */ public class JavaUserDefinedScalarFunctions { /** * Accumulator for test requiresOver. */ public static class AccumulatorOver extends Tuple2<Long, Integer> {} /** * Test for requiresOver. */ public static class OverAgg0 extends AggregateFunction<Long, AccumulatorOver> { @Override public AccumulatorOver createAccumulator() { return new AccumulatorOver(); } @Override public Long getValue(AccumulatorOver accumulator) { return 1L; } //Overloaded accumulate method public void accumulate(AccumulatorOver accumulator, long iValue, int iWeight) { } @Override public boolean requiresOver() { return true; } } /** * Increment input. */ public static class JavaFunc0 extends ScalarFunction { public long eval(Long l) { return l + 1; } } /** * Concatenate inputs as strings. */ public static class JavaFunc1 extends ScalarFunction { public String eval(Integer a, int b, Long c) { return a + " and " + b + " and " + c; } } /** * Append product to string. */ public static class JavaFunc2 extends ScalarFunction { public String eval(String s, Integer... a) { int m = 1; for (int n : a) { m *= n; } return s + m; } } /** * Test overloading. */ public static class JavaFunc3 extends ScalarFunction { public int eval(String a, int... b) { return b.length; } public String eval(String c) { return c; } } /** * Concatenate arrays as strings. */ public static class JavaFunc4 extends ScalarFunction { public String eval(Integer[] a, String[] b) { return Arrays.toString(a) + " and " + Arrays.toString(b); } } /** * Testing open method is called. */ public static class UdfWithOpen extends ScalarFunction { private boolean isOpened = false; @Override public void open(FunctionContext context) throws Exception { super.open(context); this.isOpened = true; } public String eval(String c) { if (!isOpened) { throw new IllegalStateException("Open method is not called!"); } return "$" + c; } } /** * Non-deterministic scalar function. */ public static class NonDeterministicUdf extends ScalarFunction { Random random = new Random(); public int eval() { return random.nextInt(); } public int eval(int v) { return v + random.nextInt(); } @Override public boolean isDeterministic() { return false; } } /** * Test for Python Scalar Function. */ public static class PythonScalarFunction extends ScalarFunction { private final String name; public PythonScalarFunction(String name) { this.name = name; } public int eval(int i, int j) { return i + j; } @Override public TypeInformation<?> getResultType(Class<?>[] signature) { return BasicTypeInfo.INT_TYPE_INFO; } @Override public FunctionLanguage getLanguage() { return FunctionLanguage.PYTHON; } @Override public String toString() { return name; } } /** * Test for Python Scalar Function. */ public static class BooleanPythonScalarFunction extends ScalarFunction { private final String name; public BooleanPythonScalarFunction(String name) { this.name = name; } public boolean eval(int i, int j) { return i + j > 1; } @Override public TypeInformation<?> getResultType(Class<?>[] signature) { return BasicTypeInfo.BOOLEAN_TYPE_INFO; } @Override public FunctionLanguage getLanguage() { return FunctionLanguage.PYTHON; } @Override public String toString() { return name; } } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.server.lookup.namespace.cache; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import io.druid.data.SearchableVersionedDataFinder; import io.druid.jackson.DefaultObjectMapper; import io.druid.java.util.common.lifecycle.Lifecycle; import io.druid.java.util.common.logger.Logger; import io.druid.query.lookup.namespace.ExtractionNamespace; import io.druid.query.lookup.namespace.ExtractionNamespaceCacheFactory; import io.druid.query.lookup.namespace.URIExtractionNamespace; import io.druid.segment.loading.LocalFileTimestampVersionFinder; import io.druid.server.lookup.namespace.URIExtractionNamespaceCacheFactory; import io.druid.server.metrics.NoopServiceEmitter; import org.joda.time.Period; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * */ @RunWith(Parameterized.class) public class NamespaceExtractionCacheManagersTest { private static final Logger log = new Logger(NamespaceExtractionCacheManagersTest.class); private static final Lifecycle lifecycle = new Lifecycle(); private static final Map<String, SearchableVersionedDataFinder> PULLERS = ImmutableMap.<String, SearchableVersionedDataFinder>of( "file", new LocalFileTimestampVersionFinder() ); private static final Map<Class<? extends ExtractionNamespace>, ExtractionNamespaceCacheFactory<?>> CACHE_FACTORIES = ImmutableMap.<Class<? extends ExtractionNamespace>, ExtractionNamespaceCacheFactory<?>>of( URIExtractionNamespace.class, new URIExtractionNamespaceCacheFactory(PULLERS) ); @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> getParameters() { ArrayList<Object[]> params = new ArrayList<>(); params.add( new Object[]{ new OffHeapNamespaceExtractionCacheManager( lifecycle, new NoopServiceEmitter(), CACHE_FACTORIES ) } ); params.add( new Object[]{ new OnHeapNamespaceExtractionCacheManager( lifecycle, new NoopServiceEmitter(), CACHE_FACTORIES ) } ); return params; } private final NamespaceExtractionCacheManager extractionCacheManager; public NamespaceExtractionCacheManagersTest( NamespaceExtractionCacheManager extractionCacheManager ) { this.extractionCacheManager = extractionCacheManager; } private static final List<String> nsList = ImmutableList.<String>of("testNs", "test.ns", "//tes-tn!s"); @Before public void setup() { // prepopulate caches for (String ns : nsList) { final ConcurrentMap<String, String> map = extractionCacheManager.getCacheMap(ns); map.put("oldNameSeed1", "oldNameSeed2"); } } @Test public void testSimpleCacheCreate() { for (String ns : nsList) { ConcurrentMap<String, String> map = extractionCacheManager.getCacheMap(ns); map.put("key", "val"); Assert.assertEquals("val", map.get("key")); Assert.assertEquals("val", extractionCacheManager.getCacheMap(ns).get("key")); } } @Test public void testSimpleCacheSwap() { for (String ns : nsList) { ConcurrentMap<String, String> map = extractionCacheManager.getCacheMap(ns + "old_cache"); map.put("key", "val"); extractionCacheManager.swapAndClearCache(ns, ns + "old_cache"); Assert.assertEquals("val", map.get("key")); Assert.assertEquals("val", extractionCacheManager.getCacheMap(ns).get("key")); ConcurrentMap<String, String> map2 = extractionCacheManager.getCacheMap(ns + "cache"); map2.put("key", "val2"); Assert.assertTrue(extractionCacheManager.swapAndClearCache(ns, ns + "cache")); Assert.assertEquals("val2", map2.get("key")); Assert.assertEquals("val2", extractionCacheManager.getCacheMap(ns).get("key")); } } @Test(expected = IllegalArgumentException.class) public void testMissingCacheThrowsIAE() { for (String ns : nsList) { ConcurrentMap<String, String> map = extractionCacheManager.getCacheMap(ns); map.put("key", "val"); Assert.assertEquals("val", map.get("key")); Assert.assertEquals("val", extractionCacheManager.getCacheMap(ns).get("key")); Assert.assertFalse(extractionCacheManager.swapAndClearCache(ns, "I don't exist")); } } @Test public void testCacheList() { List<String> nsList = new ArrayList<String>(NamespaceExtractionCacheManagersTest.nsList); for (String ns : nsList) { extractionCacheManager.implData.put(ns, new NamespaceExtractionCacheManager.NamespaceImplData(null, null, null)); } List<String> retvalList = Lists.newArrayList(extractionCacheManager.getKnownIDs()); Collections.sort(nsList); Collections.sort(retvalList); Assert.assertArrayEquals(nsList.toArray(), retvalList.toArray()); } @Test public void testNoDeleteNonexistant() { Assert.assertFalse(extractionCacheManager.delete("I don't exist")); } @Test public void testDeleteOnScheduleFail() throws Exception { final String id = "SOME_ID"; Assert.assertFalse(extractionCacheManager.scheduleAndWait( id, new URIExtractionNamespace( new URI("file://tmp/I_DONT_REALLY_EXIST" + UUID.randomUUID().toString()), null, null, new URIExtractionNamespace.JSONFlatDataParser( new DefaultObjectMapper(), "key", "val" ), Period.millis(10000), null ), 500 )); Assert.assertEquals(ImmutableSet.copyOf(nsList), extractionCacheManager.getKnownIDs()); } public static void waitFor(Future<?> future) throws InterruptedException { while (!future.isDone()) { try { future.get(); } catch (ExecutionException e) { log.error(e.getCause(), "Error waiting"); throw Throwables.propagate(e.getCause()); } } } }
/* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved Apache 2.0 License Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests; import android.annotation.TargetApi; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Build; import android.preference.PreferenceManager; import com.google.android.gcm.GCMRegistrar; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.microsoft.windowsazure.mobileservices.MobileServiceClient; import com.microsoft.windowsazure.mobileservices.MobileServiceException; import com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush; import com.microsoft.windowsazure.mobileservices.notifications.Registration; import com.microsoft.windowsazure.mobileservices.notifications.RegistrationCallback; import com.microsoft.windowsazure.mobileservices.notifications.TemplateRegistration; import com.microsoft.windowsazure.mobileservices.notifications.TemplateRegistrationCallback; import com.microsoft.windowsazure.mobileservices.notifications.UnregisterCallback; import com.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestCase; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestExecutionCallback; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestGroup; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestResult; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.TestStatus; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.push.GCMMessageHelper; import com.microsoft.windowsazure.mobileservices.zumoe2etestapp.push.GCMMessageManager; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; public class EnhancedPushTests extends TestGroup { private static final String tableName = "droidPushTest"; private static final String DEFAULT_REGISTRATION_NAME = "$Default"; private static final String REGISTRATION_NAME_STORAGE_KEY = "__NH_REG_NAME_"; private boolean isNetBackend = true; /* * Pointer to the main activity used to register with GCM */ public static MainActivity mainActivity; public static String registrationId; public EnhancedPushTests(boolean isNetBackend) { super("Enhanced Push tests"); this.isNetBackend = isNetBackend; // Notification Roundtrip Tests this.addTest(createGCMRegisterTest()); String json = "'Notification Hub test notification'".replace('\'', '\"'); this.addTest(createNativePushTestWithRefresh("Native Notification Roundtrip - Simple payload - With Refresh", "tag1", json)); json = "'Notification Hub test notification'".replace('\'', '\"'); this.addTest(createNativePushTest("Native Notification Roundtrip - Simple payload", "tag1", json)); json = "{'name':'John Doe','age':'33'}".replace('\'', '\"'); this.addTest(createNativePushTest("Native Notification Roundtrip - Complex payload", "tag2", json)); this.addTest(createNativePushTest("Native Notification Roundtrip - No Tag", null, json)); String templateNotification = "{'fullName':'John Doe'}".replace('\'', '\"'); String template = "{'data':{'user':'$(fullName)'}}".replace('\'', '\"'); String expectedPayload = "{'user':'John Doe'}".replace('\'', '\"'); this.addTest(createTemplatePushTest("Template Notification Roundtrip - Tag", "tag4", templateNotification, "templateTag", template, expectedPayload)); this.addTest(createTemplatePushTest("Template Notification Roundtrip - No Tag", null, templateNotification, "templateNoTag", template, expectedPayload)); this.addTest(createReRegisterNativeTestCase("Register native - Register / Unregister / Register / Unregister")); this.addTest(createReRegisterTemplateTestCase("Register template - Register / Unregister / Register / Unregister", UUID.randomUUID().toString())); this.addTest(createUnregisterNativeNonExistingTestCase("Unregister native - Non existing")); this.addTest(createUnregisterNativeUnexistingRegistrationTestCase("Unregister native - Unexisting registration")); this.addTest(createUnregisterTemplateNonExistingTestCase("Unregister template - Non existing", UUID.randomUUID().toString())); this.addTest(createUnregisterTemplateUnexistingRegistrationTestCase("Unregister template - Unexisting registration", UUID.randomUUID().toString())); this.addTest(createUnregisterAllUnregisterNativeTestCase( "Unregister all - Register native / Register template / Unregister all / Unregister native - Unexisting registration", UUID.randomUUID() .toString())); this.addTest(createUnregisterAllUnregisterTemplateTestCase( "Unregister all - Register native / Register template / Unregister all / Unregister template - Unexisting registration", UUID.randomUUID() .toString())); this.addTest(createCheckIsRefreshNeeded("Retrieve existing registrations on first connection")); // With Callbacks this.addTest(RegisterNativeWithCallbackTestCase("Register Native With Callback")); this.addTest(RegisterTemplateWithCallbackTestCase("Register Template With Callback", "template1")); this.addTest(UnRegisterNativeWithCallbackTestCase("UnRegister Native With Callback")); this.addTest(UnRegisterTemplateWithCallbackTestCase("UnRegister Template With Callback", "template1")); this.addTest(UnRegisterAllNativeWithCallbackTestCase("UnRegister All Native With Callback")); this.addTest(UnRegisterAllTemplateWithCallbackTestCase("UnRegister All Template With Callback", "template1")); this.addTest(createGCMUnregisterTest()); } public static void clearNotificationHubStorageData() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.getInstance()); Editor editor = sharedPreferences.edit(); Set<String> keys = sharedPreferences.getAll().keySet(); for (String key : keys) { if (key.startsWith("__NH_")) { editor.remove(key); } } editor.commit(); } public static void clearRegistrationsStorageData() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.getInstance()); Editor editor = sharedPreferences.edit(); Set<String> keys = sharedPreferences.getAll().keySet(); for (String key : keys) { if (key.startsWith("REGISTRATION_NAME_STORAGE_KEY")) { editor.remove(key); } } editor.commit(); } private Registration register(TestCase test, MobileServicePush hub, String gcmId, String[] tags) throws InterruptedException, ExecutionException { test.log("Register Native with GCMID = " + gcmId); if (tags != null && tags.length > 0) { for (String tag : tags) { test.log("Using tag: " + tag); } } return hub.register(gcmId, tags).get(); } private void unregister(TestCase test, MobileServicePush hub) throws InterruptedException, ExecutionException { test.log("Unregister Native"); hub.unregister().get(); } private TemplateRegistration registerTemplate(TestCase test, MobileServicePush hub, String gcmId, String templateName, String[] tags) throws InterruptedException, ExecutionException { String template = "{\"time_to_live\": 108, \"delay_while_idle\": true, \"data\": { \"message\": \"$(msg)\" } }"; return registerTemplate(test, hub, gcmId, templateName, template, tags); } private TemplateRegistration registerTemplate(TestCase test, MobileServicePush hub, String gcmId, String templateName, String template, String[] tags) throws InterruptedException, ExecutionException { test.log("Register with GCMID = " + gcmId); test.log("Register with templateName = " + templateName); if (tags != null && tags.length > 0) { for (String tag : tags) { test.log("Using tag: " + tag); } } return hub.registerTemplate(gcmId, templateName, template, tags).get(); } private void unregisterTemplate(TestCase test, MobileServicePush hub, String templateName) throws InterruptedException, ExecutionException { test.log("UnregisterTemplate with templateName = " + templateName); hub.unregisterTemplate(templateName).get(); } private void unregisterAll(TestCase test, MobileServicePush hub, String gcmId) throws InterruptedException, ExecutionException { test.log("Unregister Native"); hub.unregisterAll(gcmId).get(); } private void addUnexistingNativeRegistration(String registrationId) { addUnexistingTemplateRegistration(DEFAULT_REGISTRATION_NAME, registrationId); } private void addUnexistingTemplateRegistration(String templateName, String registrationId) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.getInstance()); Editor editor = sharedPreferences.edit(); editor.putString(REGISTRATION_NAME_STORAGE_KEY + templateName, registrationId); editor.commit(); } // Register Native Tests private int getRegistrationCountInLocalStorage() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.getInstance()); int regCount = 0; for (String key : preferences.getAll().keySet()) { if (key.startsWith("__NH_REG_NAME_")) { regCount++; } } return regCount; } // Register Template Tests private TestCase createReRegisterNativeTestCase(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); Registration reg1 = register(this, MobileServicePush, gcmId, (String[]) null); unregister(this, MobileServicePush); Registration reg2 = register(this, MobileServicePush, gcmId, (String[]) null); if (reg2.getRegistrationId().equals(reg1.getRegistrationId())) { result.setStatus(TestStatus.Failed); } unregister(this, MobileServicePush); callback.onTestComplete(this, result); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } // Unregister Native Tests private TestCase createReRegisterTemplateTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); TemplateRegistration reg1 = registerTemplate(this, MobileServicePush, gcmId, templateName, (String[]) null); unregisterTemplate(this, MobileServicePush, templateName); TemplateRegistration reg2 = registerTemplate(this, MobileServicePush, gcmId, templateName + "1", (String[]) null); if (reg2.getRegistrationId().equals(reg1.getRegistrationId())) { result.setStatus(TestStatus.Failed); } unregisterTemplate(this, MobileServicePush, templateName); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } private TestCase createUnregisterNativeNonExistingTestCase(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); unregister(this, MobileServicePush); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } // Unregister Template Tests private TestCase createUnregisterNativeUnexistingRegistrationTestCase(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); String gcmId = UUID.randomUUID().toString(); Registration registration = register(this, MobileServicePush, gcmId, (String[]) null); final String registrationId = registration.getRegistrationId(); unregister(this, MobileServicePush); addUnexistingNativeRegistration(registrationId); unregister(this, MobileServicePush); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); if (!isNetBackend) { register.setExpectedExceptionClass(MobileServiceException.class); } return register; } private TestCase createUnregisterTemplateNonExistingTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); unregisterTemplate(this, MobileServicePush, templateName); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } // Unregister All Tests private TestCase createUnregisterTemplateUnexistingRegistrationTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); TemplateRegistration templateRegistration = registerTemplate(this, MobileServicePush, UUID.randomUUID().toString(), templateName, (String[]) null); final String registrationId = templateRegistration.getRegistrationId(); unregisterTemplate(that, MobileServicePush, templateName); addUnexistingTemplateRegistration(templateName, registrationId); unregisterTemplate(that, MobileServicePush, templateName); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); if (!isNetBackend) { register.setExpectedExceptionClass(MobileServiceException.class); } return register; } private TestCase createUnregisterAllUnregisterNativeTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); unregisterAll(this, MobileServicePush, gcmId); Registration nativeRegistration = register(this, MobileServicePush, gcmId, (String[]) null); final String registrationId = nativeRegistration.getRegistrationId(); registerTemplate(this, MobileServicePush, gcmId, templateName, (String[]) null); unregisterAll(this, MobileServicePush, gcmId); addUnexistingNativeRegistration(registrationId); unregister(this, MobileServicePush); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); if (!isNetBackend) { register.setExpectedExceptionClass(MobileServiceException.class); } return register; } private TestCase createUnregisterAllUnregisterTemplateTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); unregisterAll(this, MobileServicePush, gcmId); register(this, MobileServicePush, gcmId, (String[]) null); TemplateRegistration templateRegistration = registerTemplate(this, MobileServicePush, gcmId, templateName, (String[]) null); final String registrationId = templateRegistration.getRegistrationId(); unregisterAll(this, MobileServicePush, gcmId); addUnexistingTemplateRegistration(templateName, registrationId); unregisterTemplate(this, MobileServicePush, templateName); callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); if (!isNetBackend) { register.setExpectedExceptionClass(MobileServiceException.class); } return register; } // Notification Roundtrip Tests private TestCase createCheckIsRefreshNeeded(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); unregisterAll(this, MobileServicePush, gcmId); register(this, MobileServicePush, gcmId, (String[]) null); registerTemplate(this, MobileServicePush, gcmId, UUID.randomUUID().toString(), (String[]) null); if (getRegistrationCountInLocalStorage() != 2) { result.setStatus(TestStatus.Failed); } callback.onTestComplete(this, result); return; } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } private TestCase createNativePushTest(String testName, final String tag, String jsonPayload) { final JsonElement orginalPayload = new JsonParser().parse(jsonPayload); JsonObject newPayload; if (orginalPayload.isJsonObject()) { newPayload = orginalPayload.getAsJsonObject(); } else { newPayload = new JsonObject(); newPayload.add("message", orginalPayload); } final JsonObject payload = newPayload; TestCase result = new TestCase(testName) { @Override protected void executeTest(final MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush MobileServicePush = client.getPush(); String[] tags = tag != null ? new String[]{tag} : null; unregisterAll(this, MobileServicePush, registrationId); register(this, MobileServicePush, registrationId, tags); GCMMessageManager.instance.clearPushMessages(); MobileServiceJsonTable table = client.getTable(tableName); JsonObject item = new JsonObject(); item.addProperty("method", "send"); item.addProperty("tag", tag); JsonObject sentPayload = new JsonObject(); sentPayload.add("data", payload); item.add("payload", sentPayload); item.addProperty("usingNH", true); JsonObject jsonObject = table.insert(item).get(); this.log("OnCompleted: " + jsonObject.toString()); TestExecutionCallback nativeUnregisterTestExecutionCallback = getNativeUnregisterTestExecutionCallback(client, tag, payload, callback); GCMMessageManager.instance.waitForPushMessage(20000, GCMMessageHelper.getPushCallback(this, payload, nativeUnregisterTestExecutionCallback)); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; result.setName(testName); return result; } private TestCase createTemplatePushTest(String testName, final String tag, final String templateNotification, final String templateName, final String template, final String expectedPayload) { TestCase result = new TestCase(testName) { @Override protected void executeTest(final MobileServiceClient client, final TestExecutionCallback callback) { try { String[] tags = tag != null ? new String[]{tag} : null; final MobileServicePush MobileServicePush = client.getPush(); unregisterAll(this, MobileServicePush, registrationId); registerTemplate(this, MobileServicePush, registrationId, templateName, template, tags); JsonElement templateNotificationJsonElement = new JsonParser().parse(templateNotification); GCMMessageManager.instance.clearPushMessages(); MobileServiceJsonTable table = client.getTable(tableName); JsonObject item = new JsonObject(); item.addProperty("method", "send"); item.addProperty("tag", tag); item.addProperty("payload", "not used"); item.addProperty("templatePush", true); item.add("templateNotification", templateNotificationJsonElement); item.addProperty("usingNH", true); JsonObject jsonObject = table.insert(item).get(); log("OnCompleted: " + jsonObject.toString()); TestExecutionCallback nativeUnregisterTestExecutionCallback = getTemplateUnregisterTestExecutionCallback(client, tag, templateName, template, templateNotification, callback); GCMMessageManager.instance.waitForPushMessage(20000, GCMMessageHelper.getPushCallback(this, expectedPayload, nativeUnregisterTestExecutionCallback)); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; result.setName(testName); return result; } private TestCase createGCMUnregisterTest() { TestCase testCase = new TestCase("Unregister from GCM") { @Override protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) { GCMRegistrar.unregister(mainActivity); log("Unregistered from GCM"); TestResult testResult = new TestResult(); testResult.setStatus(TestStatus.Passed); testResult.setTestCase(this); callback.onTestComplete(this, testResult); } }; return testCase; } private TestCase createGCMRegisterTest() { TestCase testCase = new TestCase("Register app with GCM") { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { try { GCMRegistrar.checkDevice(mainActivity); GCMRegistrar.checkManifest(mainActivity); String registrationId = GCMRegistrar.getRegistrationId(mainActivity); EnhancedPushTests.registrationId = registrationId; log("Registration ID: " + EnhancedPushTests.registrationId); if ("".equals(registrationId)) { GCMRegistrar.register(mainActivity, mainActivity.getGCMSenderId()); log("Called GCMRegistrar.register"); GCMMessageManager.instance.waitForRegistrationMessage(20000, GCMMessageHelper.getRegistrationCallBack(this, callback, EnhancedPushTests.class)); } else { TestResult testResult = new TestResult(); testResult.setTestCase(this); testResult.setStatus(TestStatus.Passed); callback.onTestComplete(this, testResult); } } catch (Exception e) { TestResult testResult = new TestResult(); testResult.setTestCase(this); testResult.setStatus(TestStatus.Failed); callback.onTestComplete(this, testResult); } } }; return testCase; } private TestExecutionCallback getNativeUnregisterTestExecutionCallback(final MobileServiceClient client, final String tag, final JsonObject payload, final TestExecutionCallback callback) { return new TestExecutionCallback() { @Override public void onTestStart(TestCase test) { return; } @Override public void onTestGroupComplete(TestGroup group, List<TestResult> results) { return; } @Override public void onTestComplete(TestCase test, TestResult result) { if (result.getStatus() == TestStatus.Failed) { callback.onTestComplete(test, result); } else { nativeUnregisterTestExecution(client, test, tag, payload, callback); } } }; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void nativeUnregisterTestExecution(final MobileServiceClient client, final TestCase test, final String tag, final JsonObject payload, final TestExecutionCallback callback) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... arg0) { try { unregister(test, client.getPush()); GCMMessageManager.instance.clearPushMessages(); MobileServiceJsonTable table = client.getTable(tableName); JsonObject item = new JsonObject(); item.addProperty("method", "send"); item.addProperty("tag", tag); JsonObject sentPayload = new JsonObject(); sentPayload.add("data", payload); item.add("payload", sentPayload); item.addProperty("usingNH", true); JsonObject jsonObject = table.insert(item).get(); test.log("OnCompleted: " + jsonObject.toString()); GCMMessageManager.instance.waitForPushMessage(20000, GCMMessageHelper.getNegativePushCallback(test, callback)); } catch (Exception exception) { callback.onTestComplete(test, test.createResultFromException(exception)); // return; } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private TestExecutionCallback getTemplateUnregisterTestExecutionCallback(final MobileServiceClient client, final String tag, final String templateName, final String template, final String templateNotification, final TestExecutionCallback callback) { return new TestExecutionCallback() { @Override public void onTestStart(TestCase test) { return; } @Override public void onTestGroupComplete(TestGroup group, List<TestResult> results) { return; } @Override public void onTestComplete(TestCase test, TestResult result) { if (result.getStatus() == TestStatus.Failed) { callback.onTestComplete(test, result); } else { templateUnregisterTestExecution(client, test, tag, templateName, template, templateNotification, callback); } } }; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void templateUnregisterTestExecution(final MobileServiceClient client, final TestCase test, final String tag, final String templateName, final String template, final String templateNotification, final TestExecutionCallback callback) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... arg0) { try { String[] tags = tag != null ? new String[]{tag} : null; registerTemplate(test, client.getPush(), templateName, template, tags); unregisterTemplate(test, client.getPush(), templateName); JsonElement templateNotificationJsonElement = new JsonParser().parse(templateNotification); GCMMessageManager.instance.clearPushMessages(); MobileServiceJsonTable table = client.getTable(tableName); JsonObject item = new JsonObject(); item.addProperty("method", "send"); item.addProperty("tag", tag); item.addProperty("payload", "not used"); item.addProperty("templatePush", true); item.add("templateNotification", templateNotificationJsonElement); item.addProperty("usingNH", true); JsonObject jsonObject = table.insert(item).get(); test.log("OnCompleted: " + jsonObject.toString()); GCMMessageManager.instance.waitForPushMessage(10000, GCMMessageHelper.getNegativePushCallback(test, callback)); } catch (Exception exception) { callback.onTestComplete(test, test.createResultFromException(exception)); // return; } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } // Test Callbacks @SuppressWarnings("deprecation") private void register(TestCase test, MobileServicePush hub, String gcmId, String[] tags, final RegistrationCallback callback) { test.log("Register Native with GCMID = " + gcmId); if (tags != null && tags.length > 0) { for (String tag : tags) { test.log("Using tag: " + tag); } } hub.register(gcmId, tags, callback); } private void registerTemplate(TestCase test, MobileServicePush hub, String gcmId, String templateName, String[] tags, TemplateRegistrationCallback callback) { String template = "{\"time_to_live\": 108, \"delay_while_idle\": true, \"data\": { \"message\": \"$(msg)\" } }"; registerTemplate(test, hub, gcmId, templateName, template, tags, callback); } @SuppressWarnings("deprecation") private void registerTemplate(TestCase test, MobileServicePush hub, String gcmId, String templateName, String template, String[] tags, TemplateRegistrationCallback callback) { test.log("Register with GCMID = " + gcmId); test.log("Register with templateName = " + templateName); if (tags != null && tags.length > 0) { for (String tag : tags) { test.log("Using tag: " + tag); } } hub.registerTemplate(gcmId, templateName, template, tags, callback); } @SuppressWarnings("deprecation") private void unregister(TestCase test, MobileServicePush hub, UnregisterCallback callback) { test.log("Unregister Native"); hub.unregister(callback); } @SuppressWarnings("deprecation") private void unregisterTemplate(TestCase test, MobileServicePush hub, String templateName, final UnregisterCallback callback) { test.log("UnregisterTemplate with templateName = " + templateName); hub.unregisterTemplate(templateName, callback); } @SuppressWarnings("deprecation") private void unregisterAll(TestCase test, MobileServicePush hub, String gcmId, final UnregisterCallback callback) { test.log("Unregister Native"); hub.unregisterAll(gcmId, callback); } private TestCase RegisterNativeWithCallbackTestCase(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); register(this, MobileServicePush, gcmId, (String[]) null, new RegistrationCallback() { @Override public void onRegister(final Registration reg1, Exception exception) { if (exception != null) { callback.onTestComplete(that, createResultFromException(exception)); return; } callback.onTestComplete(that, result); return; } }); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } private TestCase RegisterTemplateWithCallbackTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); registerTemplate(this, MobileServicePush, gcmId, templateName, (String[]) null, new TemplateRegistrationCallback() { @Override public void onRegister(final TemplateRegistration reg1, Exception exception) { if (exception != null) { callback.onTestComplete(that, createResultFromException(exception)); return; } callback.onTestComplete(that, result); return; } }); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } private TestCase UnRegisterNativeWithCallbackTestCase(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); unregister(this, MobileServicePush, new UnregisterCallback() { @Override public void onUnregister(Exception exception) { if (exception != null) { callback.onTestComplete(that, createResultFromException(exception)); return; } callback.onTestComplete(that, result); return; } }); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } private TestCase UnRegisterTemplateWithCallbackTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); unregisterTemplate(this, MobileServicePush, templateName, new UnregisterCallback() { @Override public void onUnregister(Exception exception) { if (exception != null) { callback.onTestComplete(that, createResultFromException(exception)); return; } callback.onTestComplete(that, result); return; } }); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); return register; } private TestCase UnRegisterAllNativeWithCallbackTestCase(String name) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); unregisterAll(that, MobileServicePush, gcmId, new UnregisterCallback() { @Override public void onUnregister(Exception exception) { if (exception != null) { callback.onTestComplete(that, createResultFromException(exception)); return; } callback.onTestComplete(that, result); return; } }); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); // register.setExpectedExceptionClass(MobileServiceException.class); return register; } private TestCase UnRegisterAllTemplateWithCallbackTestCase(String name, final String templateName) { TestCase register = new TestCase() { @Override protected void executeTest(MobileServiceClient client, final TestExecutionCallback callback) { final TestCase that = this; try { final MobileServicePush MobileServicePush = client.getPush(); final TestResult result = new TestResult(); result.setStatus(TestStatus.Passed); result.setTestCase(this); final String gcmId = UUID.randomUUID().toString(); unregisterAll(that, MobileServicePush, gcmId, new UnregisterCallback() { @Override public void onUnregister(Exception exception) { if (exception != null) { callback.onTestComplete(that, createResultFromException(exception)); return; } callback.onTestComplete(that, result); return; } }); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; register.setName(name); // register.setExpectedExceptionClass(MobileServiceException.class); return register; } private TestCase createNativePushTestWithRefresh(String testName, final String tag, String jsonPayload) { final JsonElement orginalPayload = new JsonParser().parse(jsonPayload); JsonObject newPayload; if (orginalPayload.isJsonObject()) { newPayload = orginalPayload.getAsJsonObject(); } else { newPayload = new JsonObject(); newPayload.add("message", orginalPayload); } final JsonObject payload = newPayload; TestCase result = new TestCase(testName) { @Override protected void executeTest(final MobileServiceClient client, final TestExecutionCallback callback) { try { final MobileServicePush mobileServicePush = client.getPush(); String[] tags = tag != null ? new String[]{tag} : null; unregisterAll(this, mobileServicePush, registrationId); removeStorageVersion(); MobileServiceClient client2 = new MobileServiceClient(client); final MobileServicePush mobileServicePush2 = client2.getPush(); register(this, mobileServicePush2, registrationId, tags); GCMMessageManager.instance.clearPushMessages(); MobileServiceJsonTable table = client.getTable(tableName); JsonObject item = new JsonObject(); item.addProperty("method", "send"); item.addProperty("tag", tag); JsonObject sentPayload = new JsonObject(); sentPayload.add("data", payload); item.add("payload", sentPayload); item.addProperty("usingNH", true); JsonObject jsonObject = table.insert(item).get(); this.log("OnCompleted: " + jsonObject.toString()); TestExecutionCallback nativeUnregisterTestExecutionCallback = getNativeUnregisterTestExecutionCallback(client, tag, payload, callback); GCMMessageManager.instance.waitForPushMessage(20000, GCMMessageHelper.getPushCallback(this, payload, nativeUnregisterTestExecutionCallback)); } catch (Exception e) { callback.onTestComplete(this, createResultFromException(e)); return; } } }; result.setName(testName); return result; } private void removeStorageVersion() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.getInstance()); Editor editor = sharedPreferences.edit(); editor.remove("__NH_STORAGE_VERSION"); editor.commit(); } }
/* Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JNAerator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.util.string; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtils { public static String htmlize(String text) { return text.startsWith("<?") || text.startsWith("<html>") ? text : "<html><body>"+ text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\n","<br>")+ "</body></html>"; } static Pattern spacePattern; public static List<String> explode(String s) { if (spacePattern == null) { spacePattern = Pattern.compile("\\s+"); } return explode(s, spacePattern); } public static List<String> explode(String s, String sep) { StringTokenizer st=new StringTokenizer(s,sep); List<String> v = new ArrayList<String>(); for (;st.hasMoreTokens();) { v.add(st.nextToken()); } return v; } /* public static final String implode(Object[] strings, String separator) { return implode(Arrays.asList(strings), separator); } */ public static String implode(double[] array, String separator) { StringBuffer out = new StringBuffer(); boolean first = true; for (double v : array) { if (first) first = false; else out.append(separator); out.append(v); } return out.toString(); } public static String implode(Object[] values) { return implode(values, ", "); } public static String implode(Object[] values, Object separator) { return implode(Arrays.asList(values), separator); } public static final <T> String implode(Iterable<T> elements, Object separator) { String sepStr = separator.toString(); StringBuilder out = new StringBuilder(); boolean first = true; for (Object s : elements) { if (s == null) continue; if (first) first = false; else out.append(sepStr); out.append(s); } return out.toString(); } public static final String implode(Iterable<?> strings) { return implode(strings, ", "); } /* public static final String implode(Collection<?> strings, String separator) { int size = 0, n = strings.size(); for (Object s : strings) if (s != null) size += s.toString().length(); StringBuffer out = new StringBuffer(size + separator.length() * (n == 0 ? 0 : n - 1)); boolean first = true; for (Object s : strings) { if (s == null) continue; if (first) first = false; else out.append(separator); out.append(s); } return out.toString(); } */ public static final List<String> explode(String string, Pattern separator) { int lastIndex = 0, len = string.length(); Matcher matcher = separator.matcher(string); List<String> ret = new LinkedList<String>(); while (matcher.find()) { String s = string.substring(lastIndex, matcher.start()); if (s.length() > 0) ret.add(s); lastIndex = matcher.end(); } String s = string.substring(lastIndex, len); if (s.length() > 0) ret.add(s); return ret; } public static String replace(String pattern, String replace, String s) { return concatWithSeparator(explode(s,pattern).toArray(new String[0]),replace); } public static final String concat(String[] a) { StringBuffer b=new StringBuffer(); for (int i=0;i<a.length;i++) b.append(a[i]); return b.toString(); } public static final String concatln(String[] a) { StringBuffer b=new StringBuffer(); int lenm=a.length-1; for (int i=0;i<lenm;i++) { b.append(a[i]); b.append("\n"); } if (lenm!=-1) b.append(a[lenm]); return b.toString(); } public static final String concatSpace(String[] a) { StringBuffer b=new StringBuffer(); int lenm=a.length-1; for (int i=0;i<lenm;i++) { b.append(a[i]); b.append(" "); } if (lenm!=-1) b.append(a[lenm]); return b.toString(); } public static final String concatWithSeparator(String[] a,String sep) { StringBuffer b=new StringBuffer(); int lenm=a.length-1; for (int i=0;i<lenm;i++) { b.append(a[i]); b.append(sep); } if (lenm!=-1) b.append(a[lenm]); return b.toString(); } public static final String javaEscape(String s) { if (s == null) return null; char c; int len=s.length(); StringBuffer b=new StringBuffer(len); for (int i=0;i<len;i++) { c=s.charAt(i); switch (c) { case '\n': b.append("\\n"); break; case '\t': b.append("\\t"); break; case '\r': b.append("\\r"); break; case '"': b.append("\""); break; case '\\': b.append("\\\\"); break; default: if (c>127||Character.isISOControl(c)) { b.append("\\u"); String nb=Integer.toString((int)c,16); int nblen=nb.length(); switch (nblen) { case 1: b.append(0); case 2: b.append(0); case 3: b.append(0); case 4: b.append(nb); break; default: throw new IllegalArgumentException("Should not happen !"); } } else b.append(c); } } return b.toString(); } public static final String javaUnEscape(String s) { char c; int len=s.length(); StringBuffer b=new StringBuffer(len); for (int i=0;i<len;i++) { c=s.charAt(i); if (c=='\\') { c=s.charAt(++i); switch (c) { case 'n': b.append('\n'); break; case 'r': b.append('\r'); break; case 't': b.append('\t'); break; case '\\': b.append('\\'); break; case '"': b.append('"'); break; case '\'': b.append('\''); break; case 'u': try { String nb=s.substring(i+1,i+5); int n=Integer.parseInt(nb,16); b.append((char)n); i+=4; } catch (Exception ex) { throw new IllegalArgumentException("Illegal unicode escaping in string \"" + s + "\" at index " + i, ex); } break; default: throw new IllegalArgumentException("Unknown character: \"\\"+String.valueOf(c)+"...\""); } } else b.append(c); } return b.toString(); } public static String capitalize(String string) { return string == null ? null : string.length() == 0 ? "" : Character.toUpperCase(string.charAt(0)) + string.substring(1); } public static String capitalize(List<String> strings, String separator) { List<String> cap = new ArrayList<String>(strings.size()); for (String s : strings) cap.add(capitalize(s)); return implode(cap, separator); } public static String uncapitalize(String string) { return string.length() == 0 ? "" : Character.toLowerCase(string.charAt(0)) + string.substring(1); } public static final String LINE_SEPARATOR; static { LINE_SEPARATOR = System.getProperty("line.separator"); } }
package de.fhpotsdam.unfolding.marker; import java.util.ArrayList; import java.util.List; import de.fhpotsdam.unfolding.UnfoldingMap; /** * Manages markers of different types. Is always connected to one map (for location to screen coordinate conversion). */ public class MarkerManager<E extends Marker> { protected UnfoldingMap map; protected List<E> markers; protected boolean bEnableDrawing; /** * Creates a MarkerManager with an empty markers list. */ public MarkerManager() { markers = new ArrayList<E>(); bEnableDrawing = true; } /** * Creates a MarkerManager with given markers. * * @param markers * The markers to add. */ public MarkerManager(List<E> markers) { this(); addMarkers(markers); } /** * Set the map to use for conversion of geo-locations to screen positions for the markers. * * @param map * The map. */ public void setMap(UnfoldingMap map) { this.map = map; } /** * Sets the markers to manage. * * @param markers * A list of markers. If null all existing markers will be removed. */ public void setMarkers(List<E> markers) { if (markers != null) { this.markers = markers; } else { // Convenient method. Users should use clearMarkers() directly. clearMarkers(); } } /** * Removes a marker from the managed markers. * * @param marker * The marker to remove. * @return Whether the list contained the given marker. */ public boolean removeMarker(E marker) { return markers.remove(marker); } /** * Removes all markers. */ public void clearMarkers() { markers.clear(); } public boolean isDrawingEnabled() { return bEnableDrawing; } public void enableDrawing() { bEnableDrawing = true; } public void disableDrawing() { bEnableDrawing = false; } /** * Toggles whether this marker manager draws all markers or none. */ public void toggleDrawing() { bEnableDrawing = !bEnableDrawing; } /** * Adds a marker to the manager marker list. * * @param marker * The marker to add. * @return Whether the marker was added or not. */ public boolean addMarker(E marker) { if (markers == null) { this.markers = new ArrayList<E>(); } if (markers.contains(marker)) return false; markers.add(marker); return true; } /** * Adds a list of markers to the managed markers. * * @param markers * A list of markers. */ public void addMarkers(List<E> markers) { if (this.markers == null) { this.markers = new ArrayList<E>(); } // TODO Only add marker if list does not contain it yet this.markers.addAll(markers); } /** * Searches marker with ID. * * @param id * The ID of the marker to find. * @return The found Marker or null if not found. */ public E findMarkerById(String id) { E foundMarker = null; for (E marker : this.markers) { if (marker.getId().equals(id)) { foundMarker = marker; } } return foundMarker; } /** * Searches list of markers with IDs. * * @param ids * The list of IDs of the markers to find. * @return The found Markers or an empty list if none found. */ public List<E> findMarkersByIds(List<String> ids) { List<E> foundMarkers = new ArrayList<E>(); for (E marker : markers) { if (ids.contains(marker.getId())) { foundMarkers.add(marker); } } return foundMarkers; } /** * Searches marker with a specific property. * * @param key * The property key to search for. * @param value * The property value to search for. * @return The first found Marker or null if not found. */ public E findMarkerByProperty(String key, Object value) { E foundMarker = null; for (E marker : this.markers) { Object foundValue = marker.getProperty(key); if (foundValue != null && foundValue.equals(value)) { foundMarker = marker; } } return foundMarker; } public E findMarkerByName(String name) { return findMarkerByProperty("Name", name); } /** * Returns all markers managed by this MarkerManager. * * @return A list of markers. */ public List<E> getMarkers() { return markers; } /** * @deprecated Replaced by {@link #getFirstHitMarker(float, float)} */ @Deprecated public Marker isInside(float checkX, float checkY) { return getFirstHitMarker(checkX, checkY); } /** * Returns the nearest marker to the given screen coordinates. * * @param checkX * The x position to check. * @param checkY * The y position to check. * @return The nearest marker, or null if no marker was hit. */ public E getNearestMarker(float checkX, float checkY) { E foundMarker = null; double minDist = Double.MAX_VALUE; for (E marker : markers) { // Distance between marker geo-location and check position in geo-location double dist = marker.getDistanceTo(map.getLocation(checkX, checkY)); if (minDist == dist) { if (marker.isInside(map, checkX, checkY)) { foundMarker = marker; } } else if (minDist > dist) { minDist = dist; foundMarker = marker; } } return foundMarker; } /** * Returns the first marker which the given screen coordinates hit. * * @param checkX * The x position to check. * @param checkY * The y position to check. * @return The hit marker, or null if no marker was hit. */ public E getFirstHitMarker(float checkX, float checkY) { E foundMarker = null; // NB: Markers should be ordered, e.g. by size ascending, i.e. big, medium, small for (E marker : markers) { // NB: If markers are order by size descending, i.e. small, medium, big // for (int i = markers.size() - 1; i >= 0; i--) { // Marker marker = markers.get(i); if (marker.isInside(map, checkX, checkY)) { foundMarker = marker; break; } } return foundMarker; } /** * Returns all hit markers. * * @param checkX * The x position to check. * @param checkY * The y position to check. * @return All hit markers, or an empty list if no marker was hit. */ public List<E> getHitMarkers(float checkX, float checkY) { List<E> hitMarkers = new ArrayList<E>(); for (E marker : markers) { if (marker.isInside(map, checkX, checkY)) { hitMarkers.add(marker); } } return hitMarkers; } /** * Internal method to draw all managed markers. */ public void draw() { if (!bEnableDrawing) return; for (Marker marker : markers) { marker.draw(map); } } }
/* * Copyright 2014-2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.routing.config; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.onlab.packet.IpAddress; import org.onosproject.TestApplicationId; import org.onosproject.core.ApplicationId; import org.onosproject.net.ConnectPoint; import org.onosproject.net.config.Config; import org.onosproject.net.config.ConfigApplyDelegate; import org.onosproject.routing.RoutingService; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BgpConfigTest { private static final ApplicationId APP_ID = new TestApplicationId(RoutingService.ROUTER_APP_ID); private static final IpAddress IP1 = IpAddress.valueOf("10.0.1.1"); private static final IpAddress IP2 = IpAddress.valueOf("10.0.2.1"); private static final IpAddress IP3 = IpAddress.valueOf("10.0.3.1"); private static final IpAddress IP4 = IpAddress.valueOf("10.0.101.1"); private static final IpAddress IP5 = IpAddress.valueOf("10.0.201.1"); public static final IpAddress IP_NON_EXIST = IpAddress.valueOf("10.101.1.1"); public static final ConnectPoint CONNECT_POINT1 = ConnectPoint. deviceConnectPoint("of:0000000000000001/1"); public static final ConnectPoint CONNECT_POINT2 = ConnectPoint. deviceConnectPoint("of:00000000000000a3/1"); private static final String JSON_TREE = "{\"" + BgpConfig.SPEAKERS + "\" : [{\"" + BgpConfig.NAME + "\" : \"bgp1\"," + "\"" + BgpConfig.CONNECT_POINT + "\" : \"of:0000000000000001/1\"," + "\"" + BgpConfig.PEERS + "\" : [" + "\"10.0.1.1\",\"10.0.2.1\",\"10.0.3.1\"]}]}"; private static final String EMPTY_JSON_TREE = "{}"; private final ObjectMapper mapper = new ObjectMapper(); private final ConfigApplyDelegate delegate = new MockCfgDelegate(); private final BgpConfig.BgpSpeakerConfig initialSpeaker = createInitialSpeaker(); private Set<BgpConfig.BgpSpeakerConfig> speakers = new HashSet<>(); private BgpConfig bgpConfig = new BgpConfig(); private BgpConfig emptyBgpConfig = new BgpConfig(); @Before public void setUp() throws Exception { JsonNode tree = new ObjectMapper().readTree(JSON_TREE); bgpConfig.init(APP_ID, "bgp-test", tree, mapper, delegate); JsonNode emptyTree = new ObjectMapper().readTree(EMPTY_JSON_TREE); emptyBgpConfig.init(APP_ID, "bgp-test", emptyTree, mapper, delegate); speakers.add(initialSpeaker); } /** * Tests if speakers can be retrieved from JSON. */ @Test public void testBgpSpeakers() throws Exception { assertEquals(speakers, bgpConfig.bgpSpeakers()); } /** * Tests if speakers can be retrieved from empty JSON. */ @Test public void testEmptyBgpSpeakers() throws Exception { assertTrue(emptyBgpConfig.bgpSpeakers().isEmpty()); } /** * Tests if speaker can be found by name. */ @Test public void testGetSpeakerWithName() throws Exception { assertNotNull(bgpConfig.getSpeakerWithName("bgp1")); assertNull(bgpConfig.getSpeakerWithName("bgp2")); } /** * Tests addition of new speaker. */ @Test public void testAddSpeaker() throws Exception { int initialSize = bgpConfig.bgpSpeakers().size(); BgpConfig.BgpSpeakerConfig newSpeaker = createNewSpeaker(); bgpConfig.addSpeaker(newSpeaker); assertEquals(initialSize + 1, bgpConfig.bgpSpeakers().size()); speakers.add(newSpeaker); assertEquals(speakers, bgpConfig.bgpSpeakers()); } /** * Tests addition of new speaker to empty configuration. */ @Test public void testAddSpeakerToEmpty() throws Exception { BgpConfig.BgpSpeakerConfig newSpeaker = createNewSpeaker(); emptyBgpConfig.addSpeaker(newSpeaker); assertFalse(emptyBgpConfig.bgpSpeakers().isEmpty()); } /** * Tests removal of existing speaker. */ @Test public void testRemoveExistingSpeaker() throws Exception { int initialSize = bgpConfig.bgpSpeakers().size(); bgpConfig.removeSpeaker("bgp1"); assertEquals(initialSize - 1, bgpConfig.bgpSpeakers().size()); } /** * Tests removal of non-existing speaker. */ @Test public void testRemoveInexistingSpeaker() throws Exception { int initialSize = bgpConfig.bgpSpeakers().size(); bgpConfig.removeSpeaker("bgp2"); assertEquals(initialSize, bgpConfig.bgpSpeakers().size()); } /** * Tests addition of new speaker. */ @Test public void testAddPeerToSpeaker() throws Exception { int initialSize = bgpConfig.getSpeakerWithName("bgp1").peers().size(); bgpConfig.addPeerToSpeaker("bgp1", IP4); assertEquals(initialSize + 1, bgpConfig.getSpeakerWithName("bgp1").peers().size()); } /** * Tests addition of new speaker when peer already exists. */ @Test public void testAddExistingPeerToSpeaker() throws Exception { int initialSize = bgpConfig.getSpeakerWithName("bgp1").peers().size(); bgpConfig.addPeerToSpeaker("bgp1", IP1); assertEquals(initialSize, bgpConfig.getSpeakerWithName("bgp1").peers().size()); } /** * Tests retrieval of speaker based on peering address. */ @Test public void testGetSpeakerFromPeer() throws Exception { assertNotNull(bgpConfig.getSpeakerFromPeer(IP1)); assertNull(bgpConfig.getSpeakerFromPeer(IP_NON_EXIST)); } /** * Tests removal of peer. */ @Test public void testRemoveExistingPeerFromSpeaker() throws Exception { int initialSize = bgpConfig.getSpeakerWithName("bgp1").peers().size(); bgpConfig.removePeerFromSpeaker(initialSpeaker, IP1); assertEquals(initialSize - 1, bgpConfig.getSpeakerWithName("bgp1").peers().size()); } /** * Tests peer removal when peer does not exist. */ @Test public void testRemoveNonExistingPeerFromSpeaker() throws Exception { int initialSize = bgpConfig.getSpeakerWithName("bgp1").peers().size(); bgpConfig.removePeerFromSpeaker(initialSpeaker, IP_NON_EXIST); assertEquals(initialSize, bgpConfig.getSpeakerWithName("bgp1").peers().size()); } /** * Tests if connections to peers are found. */ @Test public void testIsConnectedToPeer() { BgpConfig.BgpSpeakerConfig speaker = createNewSpeaker(); assertTrue(speaker.isConnectedToPeer(IP4)); assertFalse(speaker.isConnectedToPeer(IP_NON_EXIST)); } private class MockCfgDelegate implements ConfigApplyDelegate { @Override public void onApply(@SuppressWarnings("rawtypes") Config config) { config.apply(); } } private BgpConfig.BgpSpeakerConfig createInitialSpeaker() { Optional<String> speakerName = Optional.of("bgp1"); ConnectPoint connectPoint = CONNECT_POINT1; Set<IpAddress> connectedPeers = new HashSet<>(Arrays.asList(IP1, IP2, IP3)); return new BgpConfig.BgpSpeakerConfig(speakerName, connectPoint, connectedPeers); } private BgpConfig.BgpSpeakerConfig createNewSpeaker() { Optional<String> speakerName = Optional.of("newSpeaker"); ConnectPoint connectPoint = CONNECT_POINT2; Set<IpAddress> connectedPeers = new HashSet<>( Arrays.asList(IP4, IP5)); return new BgpConfig.BgpSpeakerConfig(speakerName, connectPoint, connectedPeers); } }
/* * Created on Dec 23, 2007 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright @2007-2013 the original author or authors. */ package org.fest.assertions; import org.fest.test.ExpectedException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import static org.fest.assertions.FailureMessages.actualIsNull; import static org.fest.assertions.FileContentComparator.LineDiff.lineDiff; import static org.fest.assertions.FileStub.newFile; import static org.fest.test.ExpectedException.none; import static org.fest.util.Strings.concat; import static org.fest.util.SystemProperties.lineSeparator; import static org.junit.Assert.*; /** * Tests for {@link FileAssert#hasSameContentAs(File)}. * * @author David DIDIER * @author Yvonne Wang * @author Alex Ruiz */ public class FileAssert_hasSameContentsAs_Test extends FileAssert_TestCase { @Rule public ExpectedException thrown = none(); private FileContentComparatorStub comparator; @Before public void onSetUp() { comparator = new FileContentComparatorStub(); } @Test public void should_pass_is_actual_and_expected_have_same_content() { file.ensureExists(); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); new FileAssert(file, comparator).hasSameContentAs(expected); } @Test public void should_fail_if_actual_is_null() { thrown.expect(AssertionError.class, actualIsNull()); new FileAssert(null).hasSameContentAs(file); } @Test public void should_fail_and_display_description_if_actual_is_null() { thrown.expect(AssertionError.class, actualIsNull("A Test")); new FileAssert(null).as("A Test").hasSameContentAs(file); } @Test public void should_fail_if_actual_and_expected_do_not_have_same_content() { file.ensureExists(); comparator.expectedLineDiffs(lineDiff(6, "abc", "xyz"), lineDiff(8, "xyz", "abc")); String message = concat("file:<c:\\f.txt> and file:<c:\\temp\\expected.txt> do not have same contents:", lineSeparator(), "line:<6>, expected:<'xyz'> but was:<'abc'>", lineSeparator(), "line:<8>, expected:<'abc'> but was:<'xyz'>"); thrown.expect(AssertionError.class, message); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); new FileAssert(file, comparator).hasSameContentAs(expected); } @Test public void should_fail_and_display_description_if_actual_and_expected_do_not_have_same_content() { file.ensureExists(); comparator.expectedLineDiffs(lineDiff(6, "abc", "xyz"), lineDiff(8, "xyz", "abc")); String message = concat( "[A Test] file:<c:\\f.txt> and file:<c:\\temp\\expected.txt> do not have same contents:", lineSeparator(), "line:<6>, expected:<'xyz'> but was:<'abc'>", lineSeparator(), "line:<8>, expected:<'abc'> but was:<'xyz'>"); thrown.expect(AssertionError.class, message); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); new FileAssert(file, comparator).as("A Test").hasSameContentAs(expected); } @Test public void should_fail_with_custom_message_if_actual_and_expected_do_not_have_same_content() { file.ensureExists(); comparator.expectedLineDiffs(lineDiff(6, "abc", "xyz"), lineDiff(8, "xyz", "abc")); thrown.expect(AssertionError.class, "My custom message"); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); new FileAssert(file, comparator).overridingErrorMessage("My custom message").hasSameContentAs(expected); } @Test public void should_fail_with_custom_message_ignoring_description_if_actual_and_expected_do_not_have_same_content() { file.ensureExists(); comparator.expectedLineDiffs(lineDiff(6, "abc", "xyz"), lineDiff(8, "xyz", "abc")); thrown.expect(AssertionError.class, "My custom message"); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); new FileAssert(file, comparator).as("A Test").overridingErrorMessage("My custom message") .hasSameContentAs(expected); } @Test public void should_fail_if_IO_error_is_thrown() { file.ensureExists(); IOException toThrow = new IOException(); comparator.exceptionToThrow(toThrow); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); try { new FileAssert(file, comparator).hasSameContentAs(expected); fail(); } catch (AssertionError e) { assertEquals("unable to compare contents of files:<c:\\f.txt> and <c:\\temp\\expected.txt>", e.getMessage()); assertSame(toThrow, e.getCause()); } } @Test public void should_fail_and_display_description_if_IO_error_is_thrown() { file.ensureExists(); IOException toThrow = new IOException(); comparator.exceptionToThrow(toThrow); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); try { new FileAssert(file, comparator).as("A Test").hasSameContentAs(expected); fail(); } catch (AssertionError e) { String expectedMessage = "[A Test] unable to compare contents of files:<c:\\f.txt> and <c:\\temp\\expected.txt>"; assertEquals(expectedMessage, e.getMessage()); assertSame(e.getCause(), toThrow); } } @Test public void should_fail_with_custom_message_if_IO_error_is_thrown() { file.ensureExists(); IOException toThrow = new IOException(); comparator.exceptionToThrow(toThrow); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); try { new FileAssert(file, comparator).overridingErrorMessage("My custom message").hasSameContentAs(expected); fail(); } catch (AssertionError e) { assertEquals("My custom message", e.getMessage()); assertSame(e.getCause(), toThrow); } } @Test public void should_fail_with_custom_message_ignoring_description_if_IO_error_is_thrown() { file.ensureExists(); IOException toThrow = new IOException(); comparator.exceptionToThrow(toThrow); FileStub expected = newFile("c:\\temp\\expected.txt").ensureExists(); try { new FileAssert(file, comparator).as("A Test").overridingErrorMessage("My custom message") .hasSameContentAs(expected); fail(); } catch (AssertionError e) { assertEquals("My custom message", e.getMessage()); assertSame(e.getCause(), toThrow); } } @Test public void should_throw_error_if_expected_is_null() { thrown.expect(NullPointerException.class); new FileAssert(file).hasSameContentAs(null); } static class FileContentComparatorStub extends FileContentComparator { private LineDiff[] diffs = new LineDiff[0]; private IOException toThrow; void expectedLineDiffs(LineDiff... newDiffs) { diffs = newDiffs; } void exceptionToThrow(IOException e) { this.toThrow = e; } @Override @NotNull LineDiff[] compareContents(@NotNull File actual, @NotNull File expected) throws IOException { if (toThrow != null) { throw toThrow; } return diffs; } } }
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.internal.gosu.parser.expressions; import gw.internal.gosu.parser.Expression; import gw.internal.gosu.parser.TypeLoaderAccess; import gw.internal.gosu.parser.TypeLord; import gw.internal.gosu.parser.Statement; import gw.internal.gosu.parser.statements.MemberAssignmentStatement; import gw.internal.gosu.parser.statements.ArrayAssignmentStatement; import gw.internal.gosu.parser.GosuParser; import gw.internal.gosu.parser.CannotExecuteGosuException; import gw.lang.parser.GosuParserTypes; import gw.lang.parser.IParsedElement; import gw.lang.parser.IExpression; import gw.lang.parser.expressions.IArrayAccessExpression; import gw.lang.reflect.IPlaceholder; import gw.lang.reflect.IType; import gw.lang.reflect.IAnnotationInfo; import gw.lang.reflect.java.JavaTypes; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * Represents a member access expression in the Gosu grammar: * <pre> * <i>array-access</i> * &lt;array-reference&gt; [ &lt;member&gt; ] * <p/> * <i>array-reference</i> * &lt;expression&gt; * <p/> * <i>member</i> * &lt;array-access&gt; * &lt;expression&gt; * </pre> * * @see gw.lang.parser.IGosuParser */ public final class ArrayAccess extends Expression implements IArrayAccessExpression { /** The array expression */ private Expression _rootExpression; /** An expression for accessing a bean member/property dynamically */ private Expression _memberExpression; private boolean _bNullSafe; public ArrayAccess() { } public Expression getRootExpression() { return _rootExpression; } public void setRootExpression( Expression rootExpression ) { _rootExpression = rootExpression; IType rootType = _rootExpression.getType(); setTypeInternal( rootType ); } public Expression getMemberExpression() { return _memberExpression; } public void setMemberExpression( Expression memberExpression ) { _memberExpression = memberExpression; } public boolean isNullSafe() { return _bNullSafe; } public void setNullSafe( boolean bNullSafe ) { _bNullSafe = bNullSafe; } /** * Evaluates the expression. */ public Object evaluate() { if( !isCompileTimeConstant() ) { //## todo: maybe make this expression evaluate directly, making a class for this seems a bit much return super.evaluate(); } throw new CannotExecuteGosuException(); } public static IType getTypeToAutoInsert( IExpression rootExpression ) { IType featureType = ((MemberAccess)rootExpression).getPropertyInfo().getFeatureType().getTypeParameters()[0]; if( (featureType.isAbstract() || featureType.isInterface()) ) { IType concreteType = GosuParser.findImpl( featureType ); if( concreteType != null ) { featureType = concreteType; } } return featureType; } public static boolean needsAutoinsert( ArrayAccess arrayAccess ) { Expression rootExpr = arrayAccess.getRootExpression(); // if the root is not a list member access, we do not auto insert if( !(rootExpr instanceof MemberAccess) || !JavaTypes.LIST().isAssignableFrom(rootExpr.getType())) { return false; } // check if the root has the Autoinsert annotation MemberAccess memberAccess = (MemberAccess)rootExpr; IType autoinsertAnnotationType = JavaTypes.AUTOINSERT(); List<IAnnotationInfo> list = autoinsertAnnotationType == null ? null : memberAccess.getPropertyInfo().getAnnotationsOfType( autoinsertAnnotationType ); if( list == null || list.isEmpty() ) { return false; } IParsedElement parent = arrayAccess.getParent(); boolean bNestedInLhs = false; boolean bNested = true; while( bNested && (parent != null) && !(parent instanceof Statement) ) { bNested = parent instanceof MemberAccess || parent instanceof ArrayAccess; parent = parent.getParent(); } if( bNested ) { IParsedElement lhsRoot = null; if( parent instanceof MemberAssignmentStatement ) { lhsRoot = ((MemberAssignmentStatement)parent).getRootExpression(); } else if ( parent instanceof ArrayAssignmentStatement ) { lhsRoot = ((ArrayAssignmentStatement)parent).getArrayAccessExpression(); } IParsedElement csr = arrayAccess; while( csr instanceof Expression ) { if( lhsRoot == csr ) { bNestedInLhs = true; break; } csr = csr.getParent(); } } return bNestedInLhs; } public IType getComponentType() { return getType(); } @Override public String toString() { return getRootExpression().toString() + "[" + getMemberExpression().toString() + "]"; } @SuppressWarnings({"UnusedDeclaration"}) public static Object getArrayElement( Object obj, int iIndex, boolean bNullSafe ) { if( obj == null ) { if( bNullSafe ) { return null; } else { throw new NullPointerException(); } } IType objType = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( obj ); if( objType.isArray() ) { return objType.getArrayComponent( obj, iIndex ); } if( obj instanceof CharSequence ) { return String.valueOf( ((CharSequence)obj).charAt( iIndex ) ); } if( obj instanceof List ) { return ((List)obj).get( iIndex ); } if( obj instanceof Collection ) { Iterator iter = ((Collection)obj).iterator(); return getElementFromIterator( iter, iIndex ); } if( obj instanceof Iterator ) { Iterator iter = (Iterator)obj; return getElementFromIterator( iter, iIndex ); } return null; } private void setTypeInternal( IType rootType ) { if( rootType.isArray() ) { setType( rootType.getComponentType() ); } else if( rootType == GosuParserTypes.STRING_TYPE() ) { setType( GosuParserTypes.STRING_TYPE() ); } else if( JavaTypes.COLLECTION().isAssignableFrom(rootType) ) { IType paramedType = TypeLord.findParameterizedType(rootType, JavaTypes.COLLECTION()); if( paramedType != null ) { setType( paramedType.getTypeParameters()[0] ); } else { setType( JavaTypes.OBJECT() ); } } else if( JavaTypes.ITERATOR().isAssignableFrom(rootType) ) { IType paramedType = TypeLord.findParameterizedType(rootType, JavaTypes.ITERATOR()); if( paramedType != null ) { setType( paramedType.getTypeParameters()[0] ); } else { setType( JavaTypes.OBJECT() ); } } else if( rootType instanceof IPlaceholder && ((IPlaceholder)rootType).isPlaceholder() ) { setType( rootType.getComponentType() ); } else { setType( JavaTypes.OBJECT() ); } } public static boolean supportsArrayAccess( IType type ) { return type.isArray() || (JavaTypes.LIST().isAssignableFrom(type) && !JavaTypes.LINKED_LIST().isAssignableFrom( type )) || JavaTypes.CHAR_SEQUENCE().isAssignableFrom(type) || (type instanceof IPlaceholder && ((IPlaceholder)type).isPlaceholder()); } private static Object getElementFromIterator( Iterator iter, int iIndex ) { int iCount = 0; while( iter.hasNext() ) { Object elem = iter.next(); if( iCount++ == iIndex ) { return elem; } } return null; } }
package com.bkromhout.minerva.ui; import android.animation.Animator; import android.animation.TimeInterpolator; import android.graphics.Rect; import android.transition.Transition; import android.util.ArrayMap; import android.view.View; import java.util.ArrayList; /** * Things to help us with UI and animation. */ public class UiUtils { /** * Used for {@link #isPointInsideView(float, float, View)} so that we only need to create the Rect once. */ private static Rect rect; /** * Determines if point falls within the bounds of the given {@code view}. * @param x X coordinate of point * @param y Y coordinate of point * @param view View object to compare * @return true if the points are within view bounds, false otherwise */ public static boolean isPointInsideView(float x, float y, View view) { if (rect == null) rect = new Rect(); view.getHitRect(rect); return rect.contains((int) x, (int) y); } /** * https://halfthought.wordpress.com/2014/11/07/reveal-transition/ * <p> * Interrupting Activity transitions can yield an OperationNotSupportedException when the transition tries to pause * the animator. Yikes! We can fix this by wrapping the Animator: */ public static class NoPauseAnimator extends Animator { private final Animator mAnimator; private final ArrayMap<AnimatorListener, AnimatorListener> mListeners = new ArrayMap<>(); public NoPauseAnimator(Animator animator) { mAnimator = animator; } @Override public void addListener(AnimatorListener listener) { AnimatorListener wrapper = new AnimatorListenerWrapper(this, listener); if (!mListeners.containsKey(listener)) { mListeners.put(listener, wrapper); mAnimator.addListener(wrapper); } } @Override public void cancel() { mAnimator.cancel(); } @Override public void end() { mAnimator.end(); } @Override public long getDuration() { return mAnimator.getDuration(); } @Override public TimeInterpolator getInterpolator() { return mAnimator.getInterpolator(); } @Override public void setInterpolator(TimeInterpolator timeInterpolator) { mAnimator.setInterpolator(timeInterpolator); } @Override public ArrayList<AnimatorListener> getListeners() { return new ArrayList<>(mListeners.keySet()); } @Override public long getStartDelay() { return mAnimator.getStartDelay(); } @Override public void setStartDelay(long delayMS) { mAnimator.setStartDelay(delayMS); } @Override public boolean isPaused() { return mAnimator.isPaused(); } @Override public boolean isRunning() { return mAnimator.isRunning(); } @Override public boolean isStarted() { return mAnimator.isStarted(); } /* We don't want to override pause or resume methods because we don't want them * to affect mAnimator. public void pause(); public void resume(); public void addPauseListener(AnimatorPauseListener listener); public void removePauseListener(AnimatorPauseListener listener); */ @Override public void removeAllListeners() { mListeners.clear(); mAnimator.removeAllListeners(); } @Override public void removeListener(AnimatorListener listener) { AnimatorListener wrapper = mListeners.get(listener); if (wrapper != null) { mListeners.remove(listener); mAnimator.removeListener(wrapper); } } @Override public Animator setDuration(long durationMS) { mAnimator.setDuration(durationMS); return this; } @Override public void setTarget(Object target) { mAnimator.setTarget(target); } @Override public void setupEndValues() { mAnimator.setupEndValues(); } @Override public void setupStartValues() { mAnimator.setupStartValues(); } @Override public void start() { mAnimator.start(); } } static class AnimatorListenerWrapper implements Animator.AnimatorListener { private final Animator mAnimator; private final Animator.AnimatorListener mListener; public AnimatorListenerWrapper(Animator animator, Animator.AnimatorListener listener) { mAnimator = animator; mListener = listener; } @Override public void onAnimationStart(Animator animator) { mListener.onAnimationStart(mAnimator); } @Override public void onAnimationEnd(Animator animator) { mListener.onAnimationEnd(mAnimator); } @Override public void onAnimationCancel(Animator animator) { mListener.onAnimationCancel(mAnimator); } @Override public void onAnimationRepeat(Animator animator) { mListener.onAnimationRepeat(mAnimator); } } /** * Shim which wraps {@link android.transition.Transition.TransitionListener} so that we can just implement the * methods that we want. */ public static class TransitionListenerAdapter implements Transition.TransitionListener { @Override public void onTransitionStart(Transition transition) { } @Override public void onTransitionEnd(Transition transition) { } @Override public void onTransitionCancel(Transition transition) { } @Override public void onTransitionPause(Transition transition) { } @Override public void onTransitionResume(Transition transition) { } } }
package de.fu_berlin.agdb.crepe.core; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.ProducerTemplate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import de.fu_berlin.agdb.crepe.algebra.Algebra; import de.fu_berlin.agdb.crepe.inputadapters.IInputAdapter; import de.fu_berlin.agdb.crepe.loader.ILoader; /** * Loads sources from XML text/files. * @author Ralf Oechsner * */ public class SourceParser implements Processor { public static final String LOADER_PACKAGE = "de.fu_berlin.agdb.crepe.loader"; public static final String INPUT_ADAPTER_PACKAGE = "de.fu_berlin.agdb.crepe.inputadapters"; public static final String LOADER_PREFIX = "loader"; public static final String INPUT_ADAPTER_PREFIX = "inputAdapter"; private static Logger logger = LogManager.getLogger(); SourceHandler loaderHandler; private URL loaderPath; private URL inputAdapterPath; private Map<String, List<List<String>>> loaderParameters; private Map<String, List<List<String>>> inputAdapterParameters; private boolean benchmarking; /** * Loads the source parser. */ public SourceParser() { loaderHandler = createAndStartLoaderHandler(); try { Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(LOADER_PACKAGE.replace(".", "/")); while (resources.hasMoreElements() && loaderPath == null) { URL url = (URL) resources.nextElement(); if(!url.toString().contains("/test-classes/")){ loaderPath = url; } } } catch (IOException e) { logger.error("Loader path could not be identified: ", e);; } try { Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(INPUT_ADAPTER_PACKAGE.replace(".", "/")); while (resources.hasMoreElements() && inputAdapterPath == null) { URL url = (URL) resources.nextElement(); if(!url.toString().contains("/test-classes/")){ inputAdapterPath = url; } } } catch (IOException e) { logger.error("InputAdapter path could not be identified: ", e);; } generateParameters(); } /** * Loads the source loader with non default paths. * @param loaderPath loader path * @param inputAdapterPath input adapter path */ public SourceParser(URL loaderPath, URL inputAdapterPath) { loaderHandler = createAndStartLoaderHandler(); this.loaderPath = loaderPath; this.inputAdapterPath = inputAdapterPath; this.generateParameters(); } private SourceHandler createAndStartLoaderHandler() { loaderHandler = new SourceHandler(Algebra.EVENT_QUEUE_URI); Thread loaderHandlerThread = new Thread(loaderHandler); loaderHandlerThread.start(); return loaderHandler; } @Override public void process(Exchange exchange) throws Exception { logger.info("Source file loaded."); if (this.benchmarking) { // no logger is used because logging is turned off for benchmarking System.out.println("Benchmark start: " + System.currentTimeMillis()); } String body = exchange.getIn().getBody(String.class); Properties properties = new Properties(); properties.load(new ByteArrayInputStream(body.getBytes("UTF-8"))); ILoader loader = parseLoader(properties); if (loader == null){ logger.error("No matching loader declaration found! Not loading source."); return; } IInputAdapter inputAdapter = parseInputAdapter(properties); if (inputAdapter == null){ logger.error("No matching input adapter declaration found! Not loading source."); return; } loaderHandler.addLoaderAndInputAdapter(new Triple<ILoader, IInputAdapter, ProducerTemplate>(loader, inputAdapter, exchange.getContext().createProducerTemplate())); } private ILoader parseLoader(Properties properties) { String loader = properties.getProperty("loader"); logger.info("Loader specified in source file: " + loader); List<List<String>> loaderParameters = this.loaderParameters.get(loader); if (loaderParameters == null) { logger.error("Loader specified in source file could not be found! Not loading source."); return null; } ILoader loaderObject = null; for (List<String> curParameters : loaderParameters) { // check if all parameters of the properties file match the parameters of the loader if (curParameters.equals(this.getPropertiesWithPrefix(LOADER_PREFIX, properties))) { // now load class loaderObject = (ILoader) this.loadClass(LOADER_PACKAGE + "." + loader, curParameters, properties, LOADER_PREFIX); break; // only first possible match is used } } return loaderObject; } private IInputAdapter parseInputAdapter(Properties properties) { IInputAdapter inputAdapterObject = null; String inputAdapter = properties.getProperty(INPUT_ADAPTER_PREFIX); List<List<String>> inputAdapterParameters = this.inputAdapterParameters.get(inputAdapter); if (inputAdapterParameters == null) { logger.error("Input adapter specified in source file could not be found! Not loading source."); return null; } for (List<String> curParameters : inputAdapterParameters) { if (equalsIgnoringOrder(curParameters, this.getPropertiesWithPrefix(INPUT_ADAPTER_PREFIX, properties))) { inputAdapterObject = (IInputAdapter) this.loadClass(INPUT_ADAPTER_PACKAGE + "." + inputAdapter, curParameters, properties, INPUT_ADAPTER_PREFIX); break; // only first possible input adapter (shouldn't be more than one anyway) } } return inputAdapterObject; } /** * Generate parameter lists of all constructors of all loaders and inputAdapters. */ private void generateParameters() { // first look for loaders in the loader package this.loaderParameters = new Hashtable<String, List<List<String>>>(); List<Class<?>> loaders = findClasses(ILoader.class, loaderPath, LOADER_PACKAGE); for (Class<?> curLoader : loaders) { this.loaderParameters.put(curLoader.getSimpleName(), classParameters(curLoader)); } logger.info("Found the following loader plugins: " + loaderParameters.keySet()); // then for input adapters in the input adapter package this.inputAdapterParameters = new Hashtable<String, List<List<String>>>(); List<Class<?>> inputAdapters = findClasses(IInputAdapter.class, inputAdapterPath, INPUT_ADAPTER_PACKAGE); for (Class<?> curInputAdapter : inputAdapters) { this.inputAdapterParameters.put(curInputAdapter.getSimpleName(), classParameters(curInputAdapter)); } logger.info("Found the following input adapter plugins: " + inputAdapterParameters.keySet()); } /** * Find all classes in a given package that implement a given interface. * @param interfaceImplemented interface classes have implement. * @param classPath path to classes. * @param packageName package name of classes. * @return list of classes in the package that implement the interface. */ private List<Class<?>> findClasses(Class<?> interfaceImplemented, URL classPath, String packageName) { List<Class<?>> classes = new ArrayList<Class<?>>(); //URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/")); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { classPath }); // filter .class files. File[] files; try { files = new File(URLDecoder.decode(classPath.getFile(), "UTF-8")).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".class"); } }); if (files == null){ return classes; } // find classes that are implementing the interface and add them to the class list for (File file : files) { String className = file.getName().replaceAll(".class$", ""); Class<?> cls; try { cls = Class.forName(packageName + "." + className, true, classLoader); if (!cls.isInterface()) { if (interfaceImplemented.isAssignableFrom(cls)) { classes.add((Class<?>) cls); } } } catch (ClassNotFoundException e) { // shouldn't happen because only classes that are found before are searched for again logger.error(e); } } } catch (UnsupportedEncodingException e1) { // also shouldn't happen because of file system encoding logger.error(e1); } return classes; } /** * Generates a list of all parameters for every constructor of a class. Every list entry represents one * constructor where the entry itself is a map which contains all the parameters. Each key is defined by a * Tag annotation and the value is the type of the parameter. * @param c class for which the parameters should be generated. * @return list of maps with constructor parameters. */ private List<List<String>> classParameters(Class<?> c) { List<List<String>> parametersList = new ArrayList<List<String>>(); Constructor<?>[] constructors = c.getConstructors(); for (Constructor<?> curConstr : constructors) { // new parameter map for every constructor List<String> parameters = new ArrayList<String>(); parametersList.add(parameters); Annotation[][] tags = curConstr.getParameterAnnotations(); for(Annotation[] annotations : tags){ for(Annotation annotation : annotations) { if (annotation instanceof Tag) { Tag tagAnn = (Tag) annotation; parameters.add(tagAnn.value()); } } } } return parametersList; } /** * Instantiate a class with given parameters for it's constructor. * @param className name of class that is instantiated (full package name). * @param parameters list of tags of parameters (in the right order). * @param prop property object where parameter values are stored. * @param prefix prefix of the input adapter / loader. * @return instantiation of the class. */ public Object loadClass(String className, List<String> parameters, Properties prop, String prefix) { try { Class<?> loaderClass = Class.forName(className); // parameter must be always Strings Class<?>[] paramTypes = new Class[parameters.size()]; for (int i = 0; i < paramTypes.length; i++) paramTypes[i] = String.class; Constructor<?> constructor = loaderClass.getConstructor(paramTypes); // build array with values in right order Object[] paramValues = new Object[parameters.size()]; int i = 0; for (String curEntry : parameters) { paramValues[i++] = prop.getProperty(prefix + "." + curEntry); } return constructor.newInstance(paramValues); } catch (ClassNotFoundException e) { // should not happen because only classes that where previously found are loaded logger.error(e); } catch (InstantiationException e) { // should also not happen because of previous reason logger.error(e); } catch (IllegalAccessException e) { // same logger.error(e); } catch (IllegalArgumentException e) { // same logger.error(e); } catch (InvocationTargetException e) { // same logger.error(e); } catch (NoSuchMethodException e) { // same logger.error(e); } catch (SecurityException e) { // same logger.error(e); } return null; } /** * Finds properties that start with a certain prefix separated by a "." and returns them in * a new list without the prefixes. * @param prefix prefix of property. * @param properties properties object. * @return subset of properties starting without the prefix. */ private List<String> getPropertiesWithPrefix(String prefix, Properties properties) { List<String> list = new ArrayList<String>(); for (String curString : properties.stringPropertyNames()) { if (curString.startsWith(prefix + ".")) { list.add(curString.substring(prefix.length() + 1)); // + 1 because of the dot } } return list; } /** * Checks if two collections (e.g. lists) contain equal objects (ignoring the order). * @param c1 first collection. * @param c2 second collection. * @return true if equal false otherwise. */ private <T> boolean equalsIgnoringOrder(Collection<T> c1, Collection<T> c2) { if (c1.size() != c2.size()) return false; if (c1.containsAll(c2)) return true; return false; } public void setBenchmarking(boolean benchmarking) { this.benchmarking = benchmarking; } }
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.stream.Stream; import javax.annotation.Nullable; /** @author awturner@google.com (Andy Turner) */ class UnnecessaryBoxedVariableCases { void positive_local() { Integer i = 0; } int positive_local_return() { Integer i = 0; return i; } Integer positive_local_addition() { Integer i = 0; return i + 1; } void positive_local_compoundAddition(Integer addend) { Integer i = 0; i += addend; int j = 0; j += i; } void positive_methodInvocation() { Integer i = 0; methodPrimitiveArg(i); } void negative_methodInvocation() { Integer i = 0; methodBoxedArg(i); } void positive_assignedValueOf() { Integer i = Integer.valueOf(0); } int positive_assignedValueOf_return() { Integer i = Integer.valueOf(0); return i; } int positive_noInitializer() { Integer i; i = 0; return i; } void negative_enhancedForLoopOverCollection(List<Integer> list) { for (Integer i : list) {} } void negative_enhancedForLoopOverWrappedArray(Integer[] array) { for (Integer i : array) {} } void positive_enhancedForLoopOverPrimitiveArray(int[] array) { for (Integer i : array) {} } final void negative_invokeMethod(Integer i) throws InterruptedException { i.wait(0); } final Object[] negative_objectArray(Long l) { return new Object[] {"", l}; } void negative_null() { Integer i = null; } void negative_null_noInitializer() { Integer i; i = null; i = 0; } void negative_null_reassignNull() { Integer i = 0; i = null; } void negative_enhancedForLoopOverPrimitiveArray_assignInLoop(int[] array) { for (Integer i : array) { i = null; } } void negative_boxedVoid() { Void v; } int negative_assignmentInReturn() { Integer myVariable; return myVariable = methodBoxedArg(42); } int positive_assignmentInReturn() { Integer myVariable; return myVariable = Integer.valueOf(42); } int positive_assignmentInReturn2() { Integer myVariable; return myVariable = Integer.valueOf(42); } int positive_hashCode() { Integer myVariable = 0; return myVariable.hashCode(); } short positive_castMethod() { Integer myVariable = 0; return myVariable.shortValue(); } int positive_castMethod_sameType() { Integer myVariable = 0; return myVariable.intValue(); } void positive_castMethod_statementExpression() { Integer myVariable = 0; myVariable.longValue(); } void negative_methodReference() { Integer myVariable = 0; Stream<Integer> stream = Stream.of(1).filter(myVariable::equals); } static void positive_parameter_staticMethod(Boolean b) { boolean a = b; } static void negative_parameter_staticMethod(Boolean b) { System.out.println("a " + b); } static boolean positive_parameter_returnType(Boolean b) { return b; } void negative_parameter_instanceMethod_nonFinal(Boolean b) { boolean a = b; } final void negative_parameter_instanceMethod_final(Boolean b) { boolean a = b; } static void negative_parameter_unused(Integer i) {} static void positive_removeNullable_parameter(@Nullable Integer i) { int j = i; } static void positive_removeNullable_localVariable() { @Nullable Integer i = 0; @javax.annotation.Nullable Integer j = 0; int k = i + j; } static int positive_nullChecked_expression(Integer i) { return checkNotNull(i); } static int positive_nullChecked_expression_message(Integer i) { return checkNotNull(i, "Null: [%s]", i); } static int positive_nullChecked_statement(Integer i) { checkNotNull(i); return i; } static int positive_nullChecked_statement_message(Integer i) { checkNotNull(i, "Null: [%s]", i); return i; } private void methodPrimitiveArg(int i) {} private Integer methodBoxedArg(Integer i) { return i; } }
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.deskclock; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.LoaderManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.Loader; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.DataSetObserver; import android.graphics.Color; import android.graphics.Rect; import android.graphics.Typeface; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Vibrator; import android.support.v7.widget.SwitchCompat; import android.transition.AutoTransition; import android.transition.Fade; import android.transition.Transition; import android.transition.TransitionManager; import android.transition.TransitionSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewTreeObserver; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CursorAdapter; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.android.datetimepicker.time.RadialPickerLayout; import com.android.datetimepicker.time.TimePickerDialog; import com.android.deskclock.alarms.AlarmStateManager; import com.android.deskclock.provider.Alarm; import com.android.deskclock.provider.AlarmInstance; import com.android.deskclock.provider.DaysOfWeek; import com.android.deskclock.widget.ActionableToastBar; import com.android.deskclock.widget.TextTime; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.HashSet; /** * AlarmClock application. */ public class AlarmClockFragment extends DeskClockFragment implements LoaderManager.LoaderCallbacks<Cursor>, TimePickerDialog.OnTimeSetListener, View.OnTouchListener { private static final float EXPAND_DECELERATION = 1f; private static final float COLLAPSE_DECELERATION = 0.7f; private static final int ANIMATION_DURATION = 300; private static final int EXPAND_DURATION = 300; private static final int COLLAPSE_DURATION = 250; private static final int ROTATE_180_DEGREE = 180; private static final float ALARM_ELEVATION = 8f; private static final float TINTED_LEVEL = 0.09f; private static final String KEY_EXPANDED_ID = "expandedId"; private static final String KEY_REPEAT_CHECKED_IDS = "repeatCheckedIds"; private static final String KEY_RINGTONE_TITLE_CACHE = "ringtoneTitleCache"; private static final String KEY_SELECTED_ALARMS = "selectedAlarms"; private static final String KEY_DELETED_ALARM = "deletedAlarm"; private static final String KEY_UNDO_SHOWING = "undoShowing"; private static final String KEY_PREVIOUS_DAY_MAP = "previousDayMap"; private static final String KEY_SELECTED_ALARM = "selectedAlarm"; private static final DeskClockExtensions sDeskClockExtensions = ExtensionsFactory .getDeskClockExtensions(); private static final int REQUEST_CODE_RINGTONE = 1; private static final long INVALID_ID = -1; // This extra is used when receiving an intent to create an alarm, but no alarm details // have been passed in, so the alarm page should start the process of creating a new alarm. public static final String ALARM_CREATE_NEW_INTENT_EXTRA = "deskclock.create.new"; // This extra is used when receiving an intent to scroll to specific alarm. If alarm // can not be found, and toast message will pop up that the alarm has be deleted. public static final String SCROLL_TO_ALARM_INTENT_EXTRA = "deskclock.scroll.to.alarm"; private FrameLayout mMainLayout; private ListView mAlarmsList; private AlarmItemAdapter mAdapter; private View mEmptyView; private View mFooterView; private Bundle mRingtoneTitleCache; // Key: ringtone uri, value: ringtone title private ActionableToastBar mUndoBar; private View mUndoFrame; private Alarm mSelectedAlarm; private long mScrollToAlarmId = INVALID_ID; private Loader mCursorLoader = null; // Saved states for undo private Alarm mDeletedAlarm; private Alarm mAddedAlarm; private boolean mUndoShowing; private Interpolator mExpandInterpolator; private Interpolator mCollapseInterpolator; private Object mAddRemoveTransition; private Object mRepeatTransition; private Object mEmptyViewTransition; //support public AlarmClockFragment() { // Basic provider required by Fragment.java } @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); mCursorLoader = getLoaderManager().initLoader(0, null, this); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) { // Inflate the layout for this fragment final View v = inflater.inflate(R.layout.alarm_clock, container, false); long expandedId = INVALID_ID; long[] repeatCheckedIds = null; long[] selectedAlarms = null; Bundle previousDayMap = null; if (savedState != null) { expandedId = savedState.getLong(KEY_EXPANDED_ID); repeatCheckedIds = savedState.getLongArray(KEY_REPEAT_CHECKED_IDS); mRingtoneTitleCache = savedState.getBundle(KEY_RINGTONE_TITLE_CACHE); mDeletedAlarm = savedState.getParcelable(KEY_DELETED_ALARM); mUndoShowing = savedState.getBoolean(KEY_UNDO_SHOWING); selectedAlarms = savedState.getLongArray(KEY_SELECTED_ALARMS); previousDayMap = savedState.getBundle(KEY_PREVIOUS_DAY_MAP); mSelectedAlarm = savedState.getParcelable(KEY_SELECTED_ALARM); } mExpandInterpolator = new DecelerateInterpolator(EXPAND_DECELERATION); mCollapseInterpolator = new DecelerateInterpolator(COLLAPSE_DECELERATION); if(Utils.isKK()) { mAddRemoveTransition = new AutoTransition(); ((Transition) mAddRemoveTransition).setDuration(ANIMATION_DURATION); mRepeatTransition = new AutoTransition(); ((Transition)mRepeatTransition).setDuration(ANIMATION_DURATION / 2); ((Transition)mRepeatTransition).setInterpolator(new AccelerateDecelerateInterpolator()); mEmptyViewTransition = new TransitionSet() .setOrdering(TransitionSet.ORDERING_SEQUENTIAL) .addTransition(new Fade(Fade.OUT)) .addTransition(new Fade(Fade.IN)) .setDuration(ANIMATION_DURATION); }else { mAddRemoveTransition = new android.support.transition.AutoTransition(); ((android.support.transition.Transition) mAddRemoveTransition).setDuration(ANIMATION_DURATION); mRepeatTransition = new AutoTransition(); ((android.support.transition.Transition)mRepeatTransition).setDuration(ANIMATION_DURATION / 2); ((android.support.transition.Transition)mRepeatTransition).setInterpolator(new AccelerateDecelerateInterpolator()); mEmptyViewTransition = new TransitionSet() .setOrdering(TransitionSet.ORDERING_SEQUENTIAL) .addTransition(new Fade(Fade.OUT)) .addTransition(new Fade(Fade.IN)) .setDuration(ANIMATION_DURATION); } boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; View menuButton = v.findViewById(R.id.menu_button); if (menuButton != null) { if (isLandscape) { menuButton.setVisibility(View.GONE); } else { menuButton.setVisibility(View.VISIBLE); setupFakeOverflowMenuButton(menuButton); } } mEmptyView = v.findViewById(R.id.alarms_empty_view); mMainLayout = (FrameLayout) v.findViewById(R.id.main); mAlarmsList = (ListView) v.findViewById(R.id.alarms_list); mUndoBar = (ActionableToastBar) v.findViewById(R.id.undo_bar); mUndoFrame = v.findViewById(R.id.undo_frame); mUndoFrame.setOnTouchListener(this); mFooterView = v.findViewById(R.id.alarms_footer_view); mFooterView.setOnTouchListener(this); mAdapter = new AlarmItemAdapter(getActivity(), expandedId, repeatCheckedIds, selectedAlarms, previousDayMap, mAlarmsList); mAdapter.registerDataSetObserver(new DataSetObserver() { private int prevAdapterCount = -1; @Override public void onChanged() { final int count = mAdapter.getCount(); if (mDeletedAlarm != null && prevAdapterCount > count) { showUndoBar(); } if ((count == 0 && prevAdapterCount > 0) || /* should fade in */ (count > 0 && prevAdapterCount == 0) /* should fade out */) { if(Utils.isKK()) { TransitionManager.beginDelayedTransition(mMainLayout,(Transition) mEmptyViewTransition); }else { android.support.transition.TransitionManager.beginDelayedTransition(mMainLayout,(android.support.transition.Transition)mEmptyViewTransition); } } mEmptyView.setVisibility(count == 0 ? View.VISIBLE : View.GONE); // Cache this adapter's count for when the adapter changes. prevAdapterCount = count; super.onChanged(); } }); if (mRingtoneTitleCache == null) { mRingtoneTitleCache = new Bundle(); } mAlarmsList.setAdapter(mAdapter); mAlarmsList.setVerticalScrollBarEnabled(true); mAlarmsList.setOnCreateContextMenuListener(this); if (mUndoShowing) { showUndoBar(); } return v; } private void setUndoBarRightMargin(int margin) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mUndoBar.getLayoutParams(); ((FrameLayout.LayoutParams) mUndoBar.getLayoutParams()) .setMargins(params.leftMargin, params.topMargin, margin, params.bottomMargin); mUndoBar.requestLayout(); } @Override public void onResume() { super.onResume(); final DeskClock activity = (DeskClock) getActivity(); if (activity.getSelectedTab() == DeskClock.ALARM_TAB_INDEX) { setFabAppearance(); setLeftRightButtonAppearance(); } if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } // Check if another app asked us to create a blank new alarm. final Intent intent = getActivity().getIntent(); if (intent.hasExtra(ALARM_CREATE_NEW_INTENT_EXTRA)) { if (intent.getBooleanExtra(ALARM_CREATE_NEW_INTENT_EXTRA, false)) { // An external app asked us to create a blank alarm. startCreatingAlarm(); } // Remove the CREATE_NEW extra now that we've processed it. intent.removeExtra(ALARM_CREATE_NEW_INTENT_EXTRA); } else if (intent.hasExtra(SCROLL_TO_ALARM_INTENT_EXTRA)) { long alarmId = intent.getLongExtra(SCROLL_TO_ALARM_INTENT_EXTRA, Alarm.INVALID_ID); if (alarmId != Alarm.INVALID_ID) { mScrollToAlarmId = alarmId; if (mCursorLoader != null && mCursorLoader.isStarted()) { // We need to force a reload here to make sure we have the latest view // of the data to scroll to. mCursorLoader.forceLoad(); } } // Remove the SCROLL_TO_ALARM extra now that we've processed it. intent.removeExtra(SCROLL_TO_ALARM_INTENT_EXTRA); } } private void hideUndoBar(boolean animate, MotionEvent event) { if (mUndoBar != null) { mUndoFrame.setVisibility(View.GONE); if (event != null && mUndoBar.isEventInToastBar(event)) { // Avoid touches inside the undo bar. return; } mUndoBar.hide(animate); } mDeletedAlarm = null; mUndoShowing = false; } private void showUndoBar() { final Alarm deletedAlarm = mDeletedAlarm; mUndoFrame.setVisibility(View.VISIBLE); mUndoBar.show(new ActionableToastBar.ActionClickedListener() { @Override public void onActionClicked() { mAddedAlarm = deletedAlarm; mDeletedAlarm = null; mUndoShowing = false; asyncAddAlarm(deletedAlarm); } }, 0, getResources().getString(R.string.alarm_deleted), true, R.string.alarm_undo, true); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(KEY_EXPANDED_ID, mAdapter.getExpandedId()); outState.putLongArray(KEY_REPEAT_CHECKED_IDS, mAdapter.getRepeatArray()); outState.putLongArray(KEY_SELECTED_ALARMS, mAdapter.getSelectedAlarmsArray()); outState.putBundle(KEY_RINGTONE_TITLE_CACHE, mRingtoneTitleCache); outState.putParcelable(KEY_DELETED_ALARM, mDeletedAlarm); outState.putBoolean(KEY_UNDO_SHOWING, mUndoShowing); outState.putBundle(KEY_PREVIOUS_DAY_MAP, mAdapter.getPreviousDaysOfWeekMap()); outState.putParcelable(KEY_SELECTED_ALARM, mSelectedAlarm); } @Override public void onDestroy() { super.onDestroy(); ToastMaster.cancelToast(); } @Override public void onPause() { super.onPause(); // When the user places the app in the background by pressing "home", // dismiss the toast bar. However, since there is no way to determine if // home was pressed, just dismiss any existing toast bar when restarting // the app. hideUndoBar(false, null); } // Callback used by TimePickerDialog /*@Override public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) { if (mSelectedAlarm == null) { // If mSelectedAlarm is null then we're creating a new alarm. Alarm a = new Alarm(); a.alert = RingtoneManager.getActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_ALARM); if (a.alert == null) { a.alert = Uri.parse("content://settings/system/alarm_alert"); } a.hour = hourOfDay; a.minutes = minute; a.enabled = true; mAddedAlarm = a; asyncAddAlarm(a); } else { mSelectedAlarm.hour = hourOfDay; mSelectedAlarm.minutes = minute; mSelectedAlarm.enabled = true; mScrollToAlarmId = mSelectedAlarm.id; asyncUpdateAlarm(mSelectedAlarm, true); mSelectedAlarm = null; } }*/ private void showLabelDialog(final Alarm alarm) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); final Fragment prev = getFragmentManager().findFragmentByTag("label_dialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); // Create and show the dialog. final LabelDialogFragment newFragment = LabelDialogFragment.newInstance(alarm, alarm.label, getTag()); newFragment.show(ft, "label_dialog"); } public void setLabel(Alarm alarm, String label) { alarm.label = label; asyncUpdateAlarm(alarm, false); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return Alarm.getAlarmsCursorLoader(getActivity()); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, final Cursor data) { mAdapter.swapCursor(data); if (mScrollToAlarmId != INVALID_ID) { scrollToAlarm(mScrollToAlarmId); mScrollToAlarmId = INVALID_ID; } } /** * Scroll to alarm with given alarm id. * * @param alarmId The alarm id to scroll to. */ private void scrollToAlarm(long alarmId) { int alarmPosition = -1; for (int i = 0; i < mAdapter.getCount(); i++) { long id = mAdapter.getItemId(i); if (id == alarmId) { alarmPosition = i; break; } } if (alarmPosition >= 0) { mAdapter.setNewAlarm(alarmId); mAlarmsList.smoothScrollToPositionFromTop(alarmPosition, 0); } else { // Trying to display a deleted alarm should only happen from a missed notification for // an alarm that has been marked deleted after use. Context context = getActivity().getApplicationContext(); Toast toast = Toast.makeText(context, R.string.missed_alarm_has_been_deleted, Toast.LENGTH_LONG); ToastMaster.setToast(toast); toast.show(); } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { mAdapter.swapCursor(null); } private void launchRingTonePicker(Alarm alarm) { mSelectedAlarm = alarm; Uri oldRingtone = Alarm.NO_RINGTONE_URI.equals(alarm.alert) ? null : alarm.alert; final Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, oldRingtone); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false); startActivityForResult(intent, REQUEST_CODE_RINGTONE); } private void saveRingtoneUri(Intent intent) { Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (uri == null) { uri = Alarm.NO_RINGTONE_URI; } mSelectedAlarm.alert = uri; // Save the last selected ringtone as the default for new alarms if (!Alarm.NO_RINGTONE_URI.equals(uri)) { RingtoneManager.setActualDefaultRingtoneUri( getActivity(), RingtoneManager.TYPE_ALARM, uri); } asyncUpdateAlarm(mSelectedAlarm, false); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case REQUEST_CODE_RINGTONE: saveRingtoneUri(data); break; default: LogUtils.w("Unhandled request code in onActivityResult: " + requestCode); } } } @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) { if (mSelectedAlarm == null) { // If mSelectedAlarm is null then we're creating a new alarm. Alarm a = new Alarm(); a.alert = RingtoneManager.getActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_ALARM); if (a.alert == null) { a.alert = Uri.parse("content://settings/system/alarm_alert"); } a.hour = hourOfDay; a.minutes = minute; a.enabled = true; mAddedAlarm = a; asyncAddAlarm(a); } else { mSelectedAlarm.hour = hourOfDay; mSelectedAlarm.minutes = minute; mSelectedAlarm.enabled = true; mScrollToAlarmId = mSelectedAlarm.id; asyncUpdateAlarm(mSelectedAlarm, true); mSelectedAlarm = null; } } public class AlarmItemAdapter extends CursorAdapter { private final Context mContext; private final LayoutInflater mFactory; private final String[] mShortWeekDayStrings; private final String[] mLongWeekDayStrings; private final int mColorLit; private final int mColorDim; private final Typeface mRobotoNormal; private final ListView mList; private long mExpandedId; private ItemHolder mExpandedItemHolder; private final HashSet<Long> mRepeatChecked = new HashSet<Long>(); private final HashSet<Long> mSelectedAlarms = new HashSet<Long>(); private Bundle mPreviousDaysOfWeekMap = new Bundle(); private final boolean mHasVibrator; private final int mCollapseExpandHeight; // This determines the order in which it is shown and processed in the UI. private final int[] DAY_ORDER = new int[] { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, }; public class ItemHolder { // views for optimization LinearLayout alarmItem; TextTime clock; TextView tomorrowLabel; SwitchCompat onoff; TextView daysOfWeek; TextView label; ImageButton delete; View expandArea; View summary; TextView clickableLabel; CheckBox repeat; LinearLayout repeatDays; Button[] dayButtons = new Button[7]; CheckBox vibrate; TextView ringtone; View hairLine; View arrow; View collapseExpandArea; // Other states Alarm alarm; } // Used for scrolling an expanded item in the list to make sure it is fully visible. private long mScrollAlarmId = AlarmClockFragment.INVALID_ID; private final Runnable mScrollRunnable = new Runnable() { @Override public void run() { if (mScrollAlarmId != AlarmClockFragment.INVALID_ID) { View v = getViewById(mScrollAlarmId); if (v != null) { Rect rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); mList.requestChildRectangleOnScreen(v, rect, false); } mScrollAlarmId = AlarmClockFragment.INVALID_ID; } } }; public AlarmItemAdapter(Context context, long expandedId, long[] repeatCheckedIds, long[] selectedAlarms, Bundle previousDaysOfWeekMap, ListView list) { super(context, null, 0); mContext = context; mFactory = LayoutInflater.from(context); mList = list; DateFormatSymbols dfs = new DateFormatSymbols(); mShortWeekDayStrings = Utils.getShortWeekdays(); mLongWeekDayStrings = dfs.getWeekdays(); Resources res = mContext.getResources(); mColorLit = res.getColor(R.color.clock_white); mColorDim = res.getColor(R.color.clock_gray); mRobotoNormal = Typeface.create("sans-serif", Typeface.NORMAL); mExpandedId = expandedId; if (repeatCheckedIds != null) { buildHashSetFromArray(repeatCheckedIds, mRepeatChecked); } if (previousDaysOfWeekMap != null) { mPreviousDaysOfWeekMap = previousDaysOfWeekMap; } if (selectedAlarms != null) { buildHashSetFromArray(selectedAlarms, mSelectedAlarms); } mHasVibrator = ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)) .hasVibrator(); mCollapseExpandHeight = (int) res.getDimension(R.dimen.collapse_expand_height); } public void removeSelectedId(int id) { mSelectedAlarms.remove(id); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!getCursor().moveToPosition(position)) { // May happen if the last alarm was deleted and the cursor refreshed while the // list is updated. LogUtils.v("couldn't move cursor to position " + position); return null; } View v; if (convertView == null) { v = newView(mContext, getCursor(), parent); } else { v = convertView; } bindView(v, mContext, getCursor()); return v; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final View view = mFactory.inflate(R.layout.alarm_time, parent, false); setNewHolder(view); return view; } /** * In addition to changing the data set for the alarm list, swapCursor is now also * responsible for preparing the transition for any added/removed items. */ @Override public synchronized Cursor swapCursor(Cursor cursor) { if (mAddedAlarm != null || mDeletedAlarm != null) { if(Utils.isKK()) TransitionManager.beginDelayedTransition(mAlarmsList, (Transition)mAddRemoveTransition); else { android.support.transition.TransitionManager.beginDelayedTransition(mAlarmsList,(android.support.transition.Transition)mAddRemoveTransition); } } final Cursor c = super.swapCursor(cursor); mAddedAlarm = null; mDeletedAlarm = null; return c; } private void setNewHolder(View view) { // standard view holder optimization final ItemHolder holder = new ItemHolder(); holder.alarmItem = (LinearLayout) view.findViewById(R.id.alarm_item); holder.tomorrowLabel = (TextView) view.findViewById(R.id.tomorrowLabel); holder.clock = (TextTime) view.findViewById(R.id.digital_clock); holder.onoff = (SwitchCompat) view.findViewById(R.id.onoff); holder.onoff.setTypeface(mRobotoNormal); holder.daysOfWeek = (TextView) view.findViewById(R.id.daysOfWeek); holder.label = (TextView) view.findViewById(R.id.label); holder.delete = (ImageButton) view.findViewById(R.id.delete); holder.summary = view.findViewById(R.id.summary); holder.expandArea = view.findViewById(R.id.expand_area); holder.hairLine = view.findViewById(R.id.hairline); holder.arrow = view.findViewById(R.id.arrow); holder.repeat = (CheckBox) view.findViewById(R.id.repeat_onoff); holder.clickableLabel = (TextView) view.findViewById(R.id.edit_label); holder.repeatDays = (LinearLayout) view.findViewById(R.id.repeat_days); holder.collapseExpandArea = view.findViewById(R.id.collapse_expand); // Build button for each day. for (int i = 0; i < 7; i++) { final Button dayButton = (Button) mFactory.inflate( R.layout.day_button, holder.repeatDays, false /* attachToRoot */); dayButton.setText(mShortWeekDayStrings[i]); dayButton.setContentDescription(mLongWeekDayStrings[DAY_ORDER[i]]); holder.repeatDays.addView(dayButton); holder.dayButtons[i] = dayButton; } holder.vibrate = (CheckBox) view.findViewById(R.id.vibrate_onoff); holder.ringtone = (TextView) view.findViewById(R.id.choose_ringtone); view.setTag(holder); } @Override public void bindView(final View view, Context context, final Cursor cursor) { final Alarm alarm = new Alarm(cursor); Object tag = view.getTag(); if (tag == null) { // The view was converted but somehow lost its tag. setNewHolder(view); } final ItemHolder itemHolder = (ItemHolder) tag; itemHolder.alarm = alarm; // We must unset the listener first because this maybe a recycled view so changing the // state would affect the wrong alarm. itemHolder.onoff.setOnCheckedChangeListener(null); itemHolder.onoff.setChecked(alarm.enabled); if (mSelectedAlarms.contains(itemHolder.alarm.id)) { setAlarmItemBackgroundAndElevation(itemHolder.alarmItem, true /* expanded */); setDigitalTimeAlpha(itemHolder, true); itemHolder.onoff.setEnabled(false); } else { itemHolder.onoff.setEnabled(true); setAlarmItemBackgroundAndElevation(itemHolder.alarmItem, false /* expanded */); setDigitalTimeAlpha(itemHolder, itemHolder.onoff.isChecked()); } itemHolder.clock.setFormat( (int)mContext.getResources().getDimension(R.dimen.alarm_label_size)); itemHolder.clock.setTime(alarm.hour, alarm.minutes); itemHolder.clock.setClickable(true); itemHolder.clock.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mSelectedAlarm = itemHolder.alarm; AlarmUtils.showTimeEditDialog(AlarmClockFragment.this, alarm); expandAlarm(itemHolder, true); itemHolder.alarmItem.post(mScrollRunnable); } }); final CompoundButton.OnCheckedChangeListener onOffListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { if (checked != alarm.enabled) { setDigitalTimeAlpha(itemHolder, checked); alarm.enabled = checked; asyncUpdateAlarm(alarm, alarm.enabled); } } }; if (mRepeatChecked.contains(alarm.id) || itemHolder.alarm.daysOfWeek.isRepeating()) { itemHolder.tomorrowLabel.setVisibility(View.GONE); } else { itemHolder.tomorrowLabel.setVisibility(View.VISIBLE); final Resources resources = getResources(); final String labelText = isTomorrow(alarm) ? resources.getString(R.string.alarm_tomorrow) : resources.getString(R.string.alarm_today); itemHolder.tomorrowLabel.setText(labelText); } itemHolder.onoff.setOnCheckedChangeListener(onOffListener); boolean expanded = isAlarmExpanded(alarm); if (expanded) { mExpandedItemHolder = itemHolder; } itemHolder.expandArea.setVisibility(expanded? View.VISIBLE : View.GONE); itemHolder.delete.setVisibility(expanded ? View.VISIBLE : View.GONE); itemHolder.summary.setVisibility(expanded? View.GONE : View.VISIBLE); itemHolder.hairLine.setVisibility(expanded ? View.GONE : View.VISIBLE); itemHolder.arrow.setRotation(expanded ? ROTATE_180_DEGREE : 0); // Set the repeat text or leave it blank if it does not repeat. final String daysOfWeekStr = alarm.daysOfWeek.toString(AlarmClockFragment.this.getActivity(), false); if (daysOfWeekStr != null && daysOfWeekStr.length() != 0) { itemHolder.daysOfWeek.setText(daysOfWeekStr); itemHolder.daysOfWeek.setContentDescription(alarm.daysOfWeek.toAccessibilityString( AlarmClockFragment.this.getActivity())); itemHolder.daysOfWeek.setVisibility(View.VISIBLE); itemHolder.daysOfWeek.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandAlarm(itemHolder, true); itemHolder.alarmItem.post(mScrollRunnable); } }); } else { itemHolder.daysOfWeek.setVisibility(View.GONE); } if (alarm.label != null && alarm.label.length() != 0) { itemHolder.label.setText(alarm.label + " "); itemHolder.label.setVisibility(View.VISIBLE); itemHolder.label.setContentDescription( mContext.getResources().getString(R.string.label_description) + " " + alarm.label); itemHolder.label.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { expandAlarm(itemHolder, true); itemHolder.alarmItem.post(mScrollRunnable); } }); } else { itemHolder.label.setVisibility(View.GONE); } itemHolder.delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDeletedAlarm = alarm; mRepeatChecked.remove(alarm.id); asyncDeleteAlarm(alarm); } }); if (expanded) { expandAlarm(itemHolder, false); } itemHolder.alarmItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isAlarmExpanded(alarm)) { collapseAlarm(itemHolder, true); } else { expandAlarm(itemHolder, true); } } }); } private void setAlarmItemBackgroundAndElevation(LinearLayout layout, boolean expanded) { if (expanded) { layout.setBackgroundColor(getTintedBackgroundColor()); if(Utils.isLP()) layout.setElevation(ALARM_ELEVATION); } else { layout.setBackgroundResource(R.drawable.alarm_background_normal); if(Utils.isLP()) layout.setElevation(0); } } private int getTintedBackgroundColor() { final int c = Utils.getCurrentHourColor(); final int red = Color.red(c) + (int) (TINTED_LEVEL * (255 - Color.red(c))); final int green = Color.green(c) + (int) (TINTED_LEVEL * (255 - Color.green(c))); final int blue = Color.blue(c) + (int) (TINTED_LEVEL * (255 - Color.blue(c))); return Color.rgb(red, green, blue); } private boolean isTomorrow(Alarm alarm) { final Calendar now = Calendar.getInstance(); final int alarmHour = alarm.hour; final int currHour = now.get(Calendar.HOUR_OF_DAY); return alarmHour < currHour || (alarmHour == currHour && alarm.minutes < now.get(Calendar.MINUTE)); } private void bindExpandArea(final ItemHolder itemHolder, final Alarm alarm) { // Views in here are not bound until the item is expanded. if (alarm.label != null && alarm.label.length() > 0) { itemHolder.clickableLabel.setText(alarm.label); } else { itemHolder.clickableLabel.setText(R.string.label); } itemHolder.clickableLabel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showLabelDialog(alarm); } }); if (mRepeatChecked.contains(alarm.id) || itemHolder.alarm.daysOfWeek.isRepeating()) { itemHolder.repeat.setChecked(true); itemHolder.repeatDays.setVisibility(View.VISIBLE); } else { itemHolder.repeat.setChecked(false); itemHolder.repeatDays.setVisibility(View.GONE); } itemHolder.repeat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Animate the resulting layout changes. if(Utils.isKK()) { TransitionManager.beginDelayedTransition(mList, (Transition)mRepeatTransition); }else { android.support.transition.TransitionManager.beginDelayedTransition(mList,(android.support.transition.Transition)mRepeatTransition); } final boolean checked = ((CheckBox) view).isChecked(); if (checked) { // Show days itemHolder.repeatDays.setVisibility(View.VISIBLE); mRepeatChecked.add(alarm.id); // Set all previously set days // or // Set all days if no previous. final int bitSet = mPreviousDaysOfWeekMap.getInt("" + alarm.id); alarm.daysOfWeek.setBitSet(bitSet); if (!alarm.daysOfWeek.isRepeating()) { alarm.daysOfWeek.setDaysOfWeek(true, DAY_ORDER); } updateDaysOfWeekButtons(itemHolder, alarm.daysOfWeek); } else { // Hide days itemHolder.repeatDays.setVisibility(View.GONE); mRepeatChecked.remove(alarm.id); // Remember the set days in case the user wants it back. final int bitSet = alarm.daysOfWeek.getBitSet(); mPreviousDaysOfWeekMap.putInt("" + alarm.id, bitSet); // Remove all repeat days alarm.daysOfWeek.clearAllDays(); } asyncUpdateAlarm(alarm, false); } }); updateDaysOfWeekButtons(itemHolder, alarm.daysOfWeek); for (int i = 0; i < 7; i++) { final int buttonIndex = i; itemHolder.dayButtons[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean isActivated = itemHolder.dayButtons[buttonIndex].isActivated(); alarm.daysOfWeek.setDaysOfWeek(!isActivated, DAY_ORDER[buttonIndex]); if (!isActivated) { turnOnDayOfWeek(itemHolder, buttonIndex); } else { turnOffDayOfWeek(itemHolder, buttonIndex); // See if this was the last day, if so, un-check the repeat box. if (!alarm.daysOfWeek.isRepeating()) { // Animate the resulting layout changes. if(Utils.isKK()) { TransitionManager.beginDelayedTransition(mList,(Transition) mRepeatTransition); }else { android.support.transition.TransitionManager.beginDelayedTransition(mList,(android.support.transition.Transition)mRepeatTransition); } itemHolder.repeat.setChecked(false); itemHolder.repeatDays.setVisibility(View.GONE); mRepeatChecked.remove(alarm.id); // Set history to no days, so it will be everyday when repeat is // turned back on mPreviousDaysOfWeekMap.putInt("" + alarm.id, DaysOfWeek.NO_DAYS_SET); } } asyncUpdateAlarm(alarm, false); } }); } if (!mHasVibrator) { itemHolder.vibrate.setVisibility(View.INVISIBLE); } else { itemHolder.vibrate.setVisibility(View.VISIBLE); if (!alarm.vibrate) { itemHolder.vibrate.setChecked(false); } else { itemHolder.vibrate.setChecked(true); } } itemHolder.vibrate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final boolean checked = ((CheckBox) v).isChecked(); alarm.vibrate = checked; asyncUpdateAlarm(alarm, false); } }); final String ringtone; if (Alarm.NO_RINGTONE_URI.equals(alarm.alert)) { ringtone = mContext.getResources().getString(R.string.silent_alarm_summary); } else { ringtone = getRingToneTitle(alarm.alert); } itemHolder.ringtone.setText(ringtone); itemHolder.ringtone.setContentDescription( mContext.getResources().getString(R.string.ringtone_description) + " " + ringtone); itemHolder.ringtone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { launchRingTonePicker(alarm); } }); } // Sets the alpha of the digital time display. This gives a visual effect // for enabled/disabled alarm while leaving the on/off switch more visible private void setDigitalTimeAlpha(ItemHolder holder, boolean enabled) { float alpha = enabled ? 1f : 0.69f; holder.clock.setAlpha(alpha); } private void updateDaysOfWeekButtons(ItemHolder holder, DaysOfWeek daysOfWeek) { HashSet<Integer> setDays = daysOfWeek.getSetDays(); for (int i = 0; i < 7; i++) { if (setDays.contains(DAY_ORDER[i])) { turnOnDayOfWeek(holder, i); } else { turnOffDayOfWeek(holder, i); } } } public void toggleSelectState(View v) { // long press could be on the parent view or one of its childs, so find the parent view v = getTopParent(v); if (v != null) { long id = ((ItemHolder)v.getTag()).alarm.id; if (mSelectedAlarms.contains(id)) { mSelectedAlarms.remove(id); } else { mSelectedAlarms.add(id); } } } private View getTopParent(View v) { while (v != null && v.getId() != R.id.alarm_item) { v = (View) v.getParent(); } return v; } public int getSelectedItemsNum() { return mSelectedAlarms.size(); } private void turnOffDayOfWeek(ItemHolder holder, int dayIndex) { final Button dayButton = holder.dayButtons[dayIndex]; dayButton.setActivated(false); dayButton.setTextColor(getResources().getColor(R.color.clock_white)); } private void turnOnDayOfWeek(ItemHolder holder, int dayIndex) { final Button dayButton = holder.dayButtons[dayIndex]; dayButton.setActivated(true); dayButton.setTextColor(Utils.getCurrentHourColor()); } /** * Does a read-through cache for ringtone titles. * * @param uri The uri of the ringtone. * @return The ringtone title. {@literal null} if no matching ringtone found. */ private String getRingToneTitle(Uri uri) { // Try the cache first String title = mRingtoneTitleCache.getString(uri.toString()); if (title == null) { // This is slow because a media player is created during Ringtone object creation. Ringtone ringTone = RingtoneManager.getRingtone(mContext, uri); title = ringTone.getTitle(mContext); if (title != null) { mRingtoneTitleCache.putString(uri.toString(), title); } } return title; } public void setNewAlarm(long alarmId) { mExpandedId = alarmId; } /** * Expands the alarm for editing. * * @param itemHolder The item holder instance. */ private void expandAlarm(final ItemHolder itemHolder, boolean animate) { // Skip animation later if item is already expanded animate &= mExpandedId != itemHolder.alarm.id; if (mExpandedItemHolder != null && mExpandedItemHolder != itemHolder && mExpandedId != itemHolder.alarm.id) { // Only allow one alarm to expand at a time. collapseAlarm(mExpandedItemHolder, animate); } bindExpandArea(itemHolder, itemHolder.alarm); mExpandedId = itemHolder.alarm.id; mExpandedItemHolder = itemHolder; // Scroll the view to make sure it is fully viewed mScrollAlarmId = itemHolder.alarm.id; // Save the starting height so we can animate from this value. final int startingHeight = itemHolder.alarmItem.getHeight(); // Set the expand area to visible so we can measure the height to animate to. setAlarmItemBackgroundAndElevation(itemHolder.alarmItem, true /* expanded */); itemHolder.expandArea.setVisibility(View.VISIBLE); itemHolder.delete.setVisibility(View.VISIBLE); if (!animate) { // Set the "end" layout and don't do the animation. itemHolder.arrow.setRotation(ROTATE_180_DEGREE); return; } // Add an onPreDrawListener, which gets called after measurement but before the draw. // This way we can check the height we need to animate to before any drawing. // Note the series of events: // * expandArea is set to VISIBLE, which causes a layout pass // * the view is measured, and our onPreDrawListener is called // * we set up the animation using the start and end values. // * the height is set back to the starting point so it can be animated down. // * request another layout pass. // * return false so that onDraw() is not called for the single frame before // the animations have started. final ViewTreeObserver observer = mAlarmsList.getViewTreeObserver(); observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { // We don't want to continue getting called for every listview drawing. if (observer.isAlive()) { observer.removeOnPreDrawListener(this); } // Calculate some values to help with the animation. final int endingHeight = itemHolder.alarmItem.getHeight(); final int distance = endingHeight - startingHeight; final int collapseHeight = itemHolder.collapseExpandArea.getHeight(); // Set the height back to the start state of the animation. itemHolder.alarmItem.getLayoutParams().height = startingHeight; // To allow the expandArea to glide in with the expansion animation, set a // negative top margin, which will animate down to a margin of 0 as the height // is increased. // Note that we need to maintain the bottom margin as a fixed value (instead of // just using a listview, to allow for a flatter hierarchy) to fit the bottom // bar underneath. FrameLayout.LayoutParams expandParams = (FrameLayout.LayoutParams) itemHolder.expandArea.getLayoutParams(); expandParams.setMargins(0, -distance, 0, collapseHeight); itemHolder.alarmItem.requestLayout(); // Set up the animator to animate the expansion. ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f) .setDuration(EXPAND_DURATION); animator.setInterpolator(mExpandInterpolator); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { Float value = (Float) animator.getAnimatedValue(); // For each value from 0 to 1, animate the various parts of the layout. itemHolder.alarmItem.getLayoutParams().height = (int) (value * distance + startingHeight); FrameLayout.LayoutParams expandParams = (FrameLayout.LayoutParams) itemHolder.expandArea.getLayoutParams(); expandParams.setMargins( 0, (int) -((1 - value) * distance), 0, collapseHeight); itemHolder.arrow.setRotation(ROTATE_180_DEGREE * value); itemHolder.summary.setAlpha(1 - value); itemHolder.hairLine.setAlpha(1 - value); itemHolder.alarmItem.requestLayout(); } }); // Set everything to their final values when the animation's done. animator.addListener(new AnimatorListener() { @Override public void onAnimationEnd(Animator animation) { // Set it back to wrap content since we'd explicitly set the height. itemHolder.alarmItem.getLayoutParams().height = LayoutParams.WRAP_CONTENT; itemHolder.arrow.setRotation(ROTATE_180_DEGREE); itemHolder.summary.setVisibility(View.GONE); itemHolder.hairLine.setVisibility(View.GONE); itemHolder.delete.setVisibility(View.VISIBLE); } @Override public void onAnimationCancel(Animator animation) { // TODO we may have to deal with cancelations of the animation. } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationStart(Animator animation) { } }); animator.start(); // Return false so this draw does not occur to prevent the final frame from // being drawn for the single frame before the animations start. return false; } }); } private boolean isAlarmExpanded(Alarm alarm) { return mExpandedId == alarm.id; } private void collapseAlarm(final ItemHolder itemHolder, boolean animate) { mExpandedId = AlarmClockFragment.INVALID_ID; mExpandedItemHolder = null; // Save the starting height so we can animate from this value. final int startingHeight = itemHolder.alarmItem.getHeight(); // Set the expand area to gone so we can measure the height to animate to. setAlarmItemBackgroundAndElevation(itemHolder.alarmItem, false /* expanded */); itemHolder.expandArea.setVisibility(View.GONE); if (!animate) { // Set the "end" layout and don't do the animation. itemHolder.arrow.setRotation(0); itemHolder.hairLine.setTranslationY(0); return; } // Add an onPreDrawListener, which gets called after measurement but before the draw. // This way we can check the height we need to animate to before any drawing. // Note the series of events: // * expandArea is set to GONE, which causes a layout pass // * the view is measured, and our onPreDrawListener is called // * we set up the animation using the start and end values. // * expandArea is set to VISIBLE again so it can be shown animating. // * request another layout pass. // * return false so that onDraw() is not called for the single frame before // the animations have started. final ViewTreeObserver observer = mAlarmsList.getViewTreeObserver(); observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { if (observer.isAlive()) { observer.removeOnPreDrawListener(this); } // Calculate some values to help with the animation. final int endingHeight = itemHolder.alarmItem.getHeight(); final int distance = endingHeight - startingHeight; // Re-set the visibilities for the start state of the animation. itemHolder.expandArea.setVisibility(View.VISIBLE); itemHolder.delete.setVisibility(View.GONE); itemHolder.summary.setVisibility(View.VISIBLE); itemHolder.hairLine.setVisibility(View.VISIBLE); itemHolder.summary.setAlpha(1); // Set up the animator to animate the expansion. ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f) .setDuration(COLLAPSE_DURATION); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animator) { Float value = (Float) animator.getAnimatedValue(); // For each value from 0 to 1, animate the various parts of the layout. itemHolder.alarmItem.getLayoutParams().height = (int) (value * distance + startingHeight); FrameLayout.LayoutParams expandParams = (FrameLayout.LayoutParams) itemHolder.expandArea.getLayoutParams(); expandParams.setMargins( 0, (int) (value * distance), 0, mCollapseExpandHeight); itemHolder.arrow.setRotation(ROTATE_180_DEGREE * (1 - value)); itemHolder.delete.setAlpha(value); itemHolder.summary.setAlpha(value); itemHolder.hairLine.setAlpha(value); itemHolder.alarmItem.requestLayout(); } }); animator.setInterpolator(mCollapseInterpolator); // Set everything to their final values when the animation's done. animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // Set it back to wrap content since we'd explicitly set the height. itemHolder.alarmItem.getLayoutParams().height = LayoutParams.WRAP_CONTENT; FrameLayout.LayoutParams expandParams = (FrameLayout.LayoutParams) itemHolder.expandArea.getLayoutParams(); expandParams.setMargins(0, 0, 0, mCollapseExpandHeight); itemHolder.expandArea.setVisibility(View.GONE); itemHolder.arrow.setRotation(0); } }); animator.start(); return false; } }); } @Override public int getViewTypeCount() { return 1; } private View getViewById(long id) { for (int i = 0; i < mList.getCount(); i++) { View v = mList.getChildAt(i); if (v != null) { ItemHolder h = (ItemHolder)(v.getTag()); if (h != null && h.alarm.id == id) { return v; } } } return null; } public long getExpandedId() { return mExpandedId; } public long[] getSelectedAlarmsArray() { int index = 0; long[] ids = new long[mSelectedAlarms.size()]; for (long id : mSelectedAlarms) { ids[index] = id; index++; } return ids; } public long[] getRepeatArray() { int index = 0; long[] ids = new long[mRepeatChecked.size()]; for (long id : mRepeatChecked) { ids[index] = id; index++; } return ids; } public Bundle getPreviousDaysOfWeekMap() { return mPreviousDaysOfWeekMap; } private void buildHashSetFromArray(long[] ids, HashSet<Long> set) { for (long id : ids) { set.add(id); } } } private void startCreatingAlarm() { // Set the "selected" alarm as null, and we'll create the new one when the timepicker // comes back. mSelectedAlarm = null; AlarmUtils.showTimeEditDialog(this, null); } private static AlarmInstance setupAlarmInstance(Context context, Alarm alarm) { ContentResolver cr = context.getContentResolver(); AlarmInstance newInstance = alarm.createInstanceAfter(Calendar.getInstance()); newInstance = AlarmInstance.addInstance(cr, newInstance); // Register instance to state manager AlarmStateManager.registerInstance(context, newInstance, true); return newInstance; } private void asyncDeleteAlarm(final Alarm alarm) { final Context context = AlarmClockFragment.this.getActivity().getApplicationContext(); final AsyncTask<Void, Void, Void> deleteTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... parameters) { // Activity may be closed at this point , make sure data is still valid if (context != null && alarm != null) { ContentResolver cr = context.getContentResolver(); AlarmStateManager.deleteAllInstances(context, alarm.id); Alarm.deleteAlarm(cr, alarm.id); sDeskClockExtensions.deleteAlarm( AlarmClockFragment.this.getActivity().getApplicationContext(), alarm.id); } return null; } }; mUndoShowing = true; deleteTask.execute(); } private void asyncAddAlarm(final Alarm alarm) { final Context context = AlarmClockFragment.this.getActivity().getApplicationContext(); final AsyncTask<Void, Void, AlarmInstance> updateTask = new AsyncTask<Void, Void, AlarmInstance>() { @Override protected AlarmInstance doInBackground(Void... parameters) { if (context != null && alarm != null) { ContentResolver cr = context.getContentResolver(); // Add alarm to db Alarm newAlarm = Alarm.addAlarm(cr, alarm); mScrollToAlarmId = newAlarm.id; // Create and add instance to db if (newAlarm.enabled) { sDeskClockExtensions.addAlarm( AlarmClockFragment.this.getActivity().getApplicationContext(), newAlarm); return setupAlarmInstance(context, newAlarm); } } return null; } @Override protected void onPostExecute(AlarmInstance instance) { if (instance != null) { AlarmUtils.popAlarmSetToast(context, instance.getAlarmTime().getTimeInMillis()); } } }; updateTask.execute(); } private void asyncUpdateAlarm(final Alarm alarm, final boolean popToast) { final Context context = AlarmClockFragment.this.getActivity().getApplicationContext(); final AsyncTask<Void, Void, AlarmInstance> updateTask = new AsyncTask<Void, Void, AlarmInstance>() { @Override protected AlarmInstance doInBackground(Void ... parameters) { ContentResolver cr = context.getContentResolver(); // Dismiss all old instances AlarmStateManager.deleteAllInstances(context, alarm.id); // Update alarm Alarm.updateAlarm(cr, alarm); if (alarm.enabled) { return setupAlarmInstance(context, alarm); } return null; } @Override protected void onPostExecute(AlarmInstance instance) { if (popToast && instance != null) { AlarmUtils.popAlarmSetToast(context, instance.getAlarmTime().getTimeInMillis()); } } }; updateTask.execute(); } @Override public boolean onTouch(View v, MotionEvent event) { hideUndoBar(true, event); return false; } @Override public void onFabClick(View view){ hideUndoBar(true, null); startCreatingAlarm(); } @Override public void setFabAppearance() { final DeskClock activity = (DeskClock) getActivity(); if (mFab == null || activity.getSelectedTab() != DeskClock.ALARM_TAB_INDEX) { return; } mFab.setVisibility(View.VISIBLE); mFab.setImageResource(R.drawable.ic_fab_plus); mFab.setContentDescription(getString(R.string.button_alarms)); } @Override public void setLeftRightButtonAppearance() { final DeskClock activity = (DeskClock) getActivity(); if (mLeftButton == null || mRightButton == null || activity.getSelectedTab() != DeskClock.ALARM_TAB_INDEX) { return; } mLeftButton.setVisibility(View.INVISIBLE); mRightButton.setVisibility(View.INVISIBLE); } }
/* * Copyright (c) 2011-2012, University of Sussex * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Sussex nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package uk.ac.susx.mlcl.lib.io; import java.io.*; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import uk.ac.susx.mlcl.lib.Checks; /** * Static utility class for file manipulation. * * @author Simon Wibberley &lt;simon.wibberley@sussex.ac.uk&gt; * @author Hamish Morgan &lt;hamish.morgan@sussex.ac.uk&gt; */ public final class Files { private Files() { } public static List<String> getFileList(String path, final String suffix) { return getFileList(new File(path), suffix, false); } public static List<String> getFileList(File path, final String suffix) { return getFileList(path, suffix, false); } public static List<String> getFileList(String path, final String suffix, final boolean includeHidden) { return getFileList(new File(path), suffix, includeHidden, false); } public static List<String> getFileList(File path, final String suffix, final boolean includeHidden) { return getFileList(path, suffix, includeHidden, false); } public static List<String> getFileList(String path, final String suffix, final boolean includeHidden, final boolean recursive) { return getFileList(new File(path), suffix, includeHidden, recursive); } public static List<String> getFileList(File path, final String suffix, final boolean includeHidden, final boolean recursive) { if (path == null) throw new NullPointerException("path is null"); if (suffix == null) throw new NullPointerException("suffix is null"); if (!path.exists()) { throw new IllegalArgumentException("path does not exist: " + path); } if (!path.isDirectory()) { throw new IllegalArgumentException( "path is not a directory: " + path); } if (!path.canRead()) { throw new IllegalArgumentException("path is not readable: " + path); } final ArrayList<String> fileList = new ArrayList<String>(); final FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (recursive) { File f = new File( dir.getAbsolutePath() + File.separator + name); if (f.isDirectory()) { List<String> subList = getFileList( f.getAbsoluteFile(), suffix, includeHidden, recursive); for (String file : subList) { String subPath = name + File.separator + file; fileList.add(subPath); } } } if (includeHidden) { return name.toLowerCase().endsWith(suffix); } else { String lc = name.toLowerCase(); return lc.endsWith(suffix) && !lc.startsWith("."); } } }; fileList.addAll(Arrays.asList(path.list(filter))); return fileList; } public static CharSequence getText(String file) throws IOException { return getText(new File(file), false, false); } public static CharSequence getText(File file) throws IOException { return getText(file, false, false); } public static CharSequence getText( String file, boolean gzip, boolean incNewline) throws IOException { return getText(new File(file), gzip, incNewline); } public static CharSequence getText( File file, boolean gzip, boolean incNewline) throws IOException { if (gzip) { return getText(new InputStreamReader( new GZIPInputStream(new FileInputStream(file))), incNewline); } else { return getText(new BufferedReader(new FileReader(file)), incNewline); } } public static CharSequence getText(Reader reader) throws IOException { return getText(reader, false); } public static final int BUFFER_SIZE = 8192; public static CharSequence getTextWholeFile(Reader in) throws IOException { final StringBuilder strbldr = new StringBuilder(); try { final char[] strbuf = new char[BUFFER_SIZE]; int read; while ((read = in.read(strbuf)) >= 0) { strbldr.append(strbuf, 0, read); } } finally { in.close(); } return strbldr; } public static CharSequence getText(Reader in, boolean incNewline) throws IOException { if (incNewline) { return getTextWholeFile(in); } final StringBuilder strbfr = new StringBuilder(); try { final BufferedReader br = (in instanceof BufferedReader) ? ((BufferedReader) in) : new BufferedReader(in); String tmpStr; while ((tmpStr = br.readLine()) != null) { strbfr.append(tmpStr); } } finally { in.close(); } return strbfr; } public static int countLines(File in) throws IOException { return countLines(new FileReader(in)); } public static int countLines(InputStream in) throws IOException { return countLines(new InputStreamReader(in)); } public static int countLines(Reader in) throws IOException { final BufferedReader br = (in instanceof BufferedReader) ? ((BufferedReader) in) : new BufferedReader(in); int count = 0; while (br.readLine() != null) { ++count; } return count; } public static File createTempDir(String prefix, String suffix, File directory) throws IOException { final File temp = File.createTempFile(prefix, suffix, directory); if (!temp.delete() || !temp.mkdir() || !temp.isDirectory()) throw new IOException("Failed to create temporary directory " + temp); return temp; } public static File createTempDir(String prefix, String suffix) throws IOException { return createTempDir(prefix, suffix, null); } @Deprecated public static final File STDIN_FILE = new File("-"); @Deprecated public static final File STDOUT_FILE = new File("-"); public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");// Charset.defaultCharset(); /* * XXX: The following fields are not final because they are changed to * "REPORT" during unit tests. Obviously this is not ideal. */ public static CodingErrorAction MALFORMED_INPUT_ACTION = CodingErrorAction.REPLACE; public static CodingErrorAction UNMAPPABLE_CHARACTER_ACTION = CodingErrorAction.REPLACE; @Deprecated public static boolean isStdin(File file) { return file.getName().equals(STDIN_FILE.getName()); } @Deprecated public static boolean isStdout(File file) { return file.getName().equals(STDOUT_FILE.getName()); } public static boolean isGzip(File file) { return file.getName().toLowerCase().endsWith(".gz"); } public static CharsetDecoder decoderFor(Charset charset) { return charset.newDecoder(). onMalformedInput(MALFORMED_INPUT_ACTION). onUnmappableCharacter(UNMAPPABLE_CHARACTER_ACTION); } public static CharsetEncoder encoderFor(Charset charset) { return charset.newEncoder(). onMalformedInput(MALFORMED_INPUT_ACTION). onUnmappableCharacter(UNMAPPABLE_CHARACTER_ACTION); } public static BufferedReader openReader( final File file, final Charset charset) throws FileNotFoundException, IOException { return new BufferedReader(new InputStreamReader( openInputStream(file), decoderFor(charset))); } public static BufferedWriter openWriter( final File file, final Charset charset) throws FileNotFoundException, IOException { return new BufferedWriter( new OutputStreamWriter(openOutputStream(file), encoderFor( charset))); } public static ReadableByteChannel openReadableByteChannel(final File file) throws FileNotFoundException, IOException, NullPointerException { if (file == null) { throw new NullPointerException("file is null"); } else if (isStdin(file)) { return Channels.newChannel(System.in); } else if (isGzip(file)) { return Channels.newChannel( new GZIPInputStream( new FileInputStream(file))); } else { return new FileInputStream(file).getChannel(); } } public static WritableByteChannel openWritableByteChannel(File file) throws FileNotFoundException, IOException, NullPointerException { if (file == null) { throw new NullPointerException("file is null"); } else if (isStdout(file)) { return Channels.newChannel(System.out); } else if (isGzip(file)) { return Channels.newChannel( new GZIPOutputStream( new FileOutputStream(file))); } else { return new FileOutputStream(file).getChannel(); } } public static InputStream openInputStream(final File file) throws FileNotFoundException, IOException { if (file == null) throw new NullPointerException(); if (isStdin(file)) { return System.in; } else if (isGzip(file)) { return new GZIPInputStream( new FileInputStream(file)); } else { return new BufferedInputStream(new FileInputStream(file)); } } public static OutputStream openOutputStream(File file) throws FileNotFoundException, IOException { if (file == null) throw new NullPointerException(); if (isStdout(file)) { return System.out; } else if (isGzip(file)) { return new GZIPOutputStream(new FileOutputStream(file)); } else { return new BufferedOutputStream(new FileOutputStream(file)); } } public static String fileName(final File file, Object thing) { if (file == null || file.getName().equals("-")) { return (thing instanceof Readable || thing instanceof InputStream) ? "stdin" : (thing instanceof Appendable || thing instanceof OutputStream) ? "stdout" : "file"; } else { return file.getName(); } } public static void readAllLines(File file, Charset charset, Collection<? super String> lines) throws FileNotFoundException, IOException { readLines(file, charset, lines); } public static List<String> readLines( File file, Charset charset) throws FileNotFoundException, IOException { return readLines(file, charset, Integer.MAX_VALUE); } public static List<String> readLines( File file, Charset charset, int limit) throws FileNotFoundException, IOException { final ArrayList<String> lines = new ArrayList<String>(); readLines(file, charset, lines, limit); return lines; } public static void readLines( File file, Charset charset, Collection<? super String> lines) throws FileNotFoundException, IOException { readLines(file, charset, lines, Integer.MAX_VALUE); } public static void readLines(File file, Charset charset, Collection<? super String> lines, int limit) throws FileNotFoundException, IOException { BufferedReader reader = null; int count = 0; try { reader = openReader(file, charset); String line = reader.readLine(); while (line != null && count < limit) { lines.add(line); line = reader.readLine(); ++count; } } finally { if (reader != null) reader.close(); } } public static void writeAllLines(File file, Charset charset, Collection<? extends String> lines) throws FileNotFoundException, IOException { BufferedWriter writer = null; try { writer = openWriter(file, charset); for (String line : lines) { writer.write(line); writer.newLine(); } } finally { if (writer != null) { writer.flush(); writer.close(); } } } public static void readAll(File file, Charset charset, StringBuilder dst) throws FileNotFoundException, IOException { BufferedReader reader = null; try { reader = openReader(file, charset); char[] buf = new char[10000]; int len = 0; while ((len = reader.read(buf)) != -1) { dst.append(buf, 0, len); } } finally { if (reader != null) reader.close(); } } public static void writeAll(File file, Charset charset, CharSequence src) throws FileNotFoundException, IOException { BufferedWriter writer = null; try { writer = openWriter(file, charset); writer.append(src); } finally { if (writer != null) { writer.flush(); writer.close(); } } } public static void writeSerialized(Object obj, File file) throws IOException { writeSerialized(obj, file, false); } public static void writeSerialized(Object obj, File file, boolean compressed) throws IOException { Checks.checkNotNull("obj", obj); Checks.checkNotNull("file", file); ObjectOutputStream oos = null; try { oos = compressed ? new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream( file))) : new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( file))); writeSerialized(obj, oos); } finally { if (oos != null) { oos.close(); } } } public static void writeSerialized(Object obj, OutputStream os) throws IOException { Checks.checkNotNull("obj", obj); Checks.checkNotNull("os", os); ObjectOutputStream oos = null; try { oos = (os instanceof ObjectOutputStream) ? (ObjectOutputStream) os : new ObjectOutputStream(os); oos.writeObject(obj); } finally { oos.flush(); } } public static Object readSerialized(File file) throws IOException, ClassNotFoundException { return readSerialized(file, false); } public static Object readSerialized(File file, boolean compressed) throws IOException, ClassNotFoundException { Checks.checkNotNull("file", file); ObjectInputStream ois = null; try { ois = compressed ? new ObjectInputStream(new GZIPInputStream(new FileInputStream( file))) : new ObjectInputStream(new BufferedInputStream(new FileInputStream( file))); return readSerialized(ois); } finally { if (ois != null) ois.close(); } } public static Object readSerialized(InputStream is) throws IOException, ClassNotFoundException { Checks.checkNotNull("is", is); ObjectInputStream ois = (is instanceof ObjectInputStream) ? (ObjectInputStream) is : new ObjectInputStream(is); return ois.readObject(); } }
/* * Copyright 2007 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.collect.ImmutableSet; import com.google.javascript.jscomp.type.FlowScope; import com.google.javascript.jscomp.type.ReverseAbstractInterpreter; import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.JSType; import java.util.Arrays; import java.util.Collection; public final class SemanticReverseAbstractInterpreterTest extends CompilerTypeTestCase { { new GoogleCodingConvention(); } private ReverseAbstractInterpreter interpreter; private TypedScope functionScope; @Override protected void setUp() throws Exception { super.setUp(); interpreter = new SemanticReverseAbstractInterpreter(registry); } public FlowScope newScope() { TypedScope globalScope = TypedScope.createGlobalScope(new Node(Token.ROOT)); functionScope = new TypedScope(globalScope, new Node(Token.FUNCTION)); return LinkedFlowScope.createEntryLattice(functionScope); } /** * Tests reverse interpretation of a NAME expression. */ public void testNameCondition() throws Exception { FlowScope blind = newScope(); Node condition = createVar(blind, "a", createNullableType(STRING_TYPE)); // true outcome. FlowScope informedTrue = interpreter. getPreciserScopeKnowingConditionOutcome(condition, blind, true); assertTypeEquals(STRING_TYPE, getVarType(informedTrue, "a")); // false outcome. FlowScope informedFalse = interpreter. getPreciserScopeKnowingConditionOutcome(condition, blind, false); assertTypeEquals(createNullableType(STRING_TYPE), getVarType(informedFalse, "a")); } /** * Tests reverse interpretation of a NOT(NAME) expression. */ public void testNegatedNameCondition() throws Exception { FlowScope blind = newScope(); Node a = createVar(blind, "a", createNullableType(STRING_TYPE)); Node condition = new Node(Token.NOT); condition.addChildToBack(a); // true outcome. FlowScope informedTrue = interpreter. getPreciserScopeKnowingConditionOutcome(condition, blind, true); assertTypeEquals(createNullableType(STRING_TYPE), getVarType(informedTrue, "a")); // false outcome. FlowScope informedFalse = interpreter. getPreciserScopeKnowingConditionOutcome(condition, blind, false); assertTypeEquals(STRING_TYPE, getVarType(informedFalse, "a")); } /** * Tests reverse interpretation of a ASSIGN expression. */ @SuppressWarnings("unchecked") public void testAssignCondition1() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.ASSIGN, createVar(blind, "a", createNullableType(OBJECT_TYPE)), createVar(blind, "b", createNullableType(OBJECT_TYPE)), ImmutableSet.of( new TypedName("a", OBJECT_TYPE), new TypedName("b", OBJECT_TYPE)), ImmutableSet.of( new TypedName("a", NULL_TYPE), new TypedName("b", NULL_TYPE))); } /** * Tests reverse interpretation of a SHEQ(NAME, NUMBER) expression. */ @SuppressWarnings("unchecked") public void testSheqCondition1() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHEQ, createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE)), createNumber(56), ImmutableSet.of(new TypedName("a", NUMBER_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE)))); } /** * Tests reverse interpretation of a SHEQ(NUMBER, NAME) expression. */ @SuppressWarnings("unchecked") public void testSheqCondition2() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHEQ, createNumber(56), createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE)), ImmutableSet.of(new TypedName("a", NUMBER_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE)))); } /** * Tests reverse interpretation of a SHEQ(NAME, NAME) expression. */ @SuppressWarnings("unchecked") public void testSheqCondition3() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHEQ, createVar(blind, "b", createUnionType(STRING_TYPE, BOOLEAN_TYPE)), createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE)), ImmutableSet.of(new TypedName("a", STRING_TYPE), new TypedName("b", STRING_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE)), new TypedName("b", createUnionType(STRING_TYPE, BOOLEAN_TYPE)))); } @SuppressWarnings("unchecked") public void testSheqCondition4() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHEQ, createVar(blind, "a", createUnionType(STRING_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(VOID_TYPE)), ImmutableSet.of(new TypedName("a", VOID_TYPE), new TypedName("b", VOID_TYPE)), ImmutableSet.of(new TypedName("a", STRING_TYPE), new TypedName("b", VOID_TYPE))); } @SuppressWarnings("unchecked") public void testSheqCondition5() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHEQ, createVar(blind, "a", createUnionType(NULL_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(VOID_TYPE)), ImmutableSet.of(new TypedName("a", VOID_TYPE), new TypedName("b", VOID_TYPE)), ImmutableSet.of(new TypedName("a", NULL_TYPE), new TypedName("b", VOID_TYPE))); } @SuppressWarnings("unchecked") public void testSheqCondition6() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHEQ, createVar(blind, "a", createUnionType(STRING_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(NUMBER_TYPE, VOID_TYPE)), ImmutableSet.of( new TypedName("a", VOID_TYPE), new TypedName("b", VOID_TYPE)), ImmutableSet.of( new TypedName("a", createUnionType(STRING_TYPE, VOID_TYPE)), new TypedName("b", createUnionType(NUMBER_TYPE, VOID_TYPE)))); } /** * Tests reverse interpretation of a SHNE(NAME, NUMBER) expression. */ @SuppressWarnings("unchecked") public void testShneCondition1() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHNE, createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE)), createNumber(56), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE))), ImmutableSet.of(new TypedName("a", NUMBER_TYPE))); } /** * Tests reverse interpretation of a SHNE(NUMBER, NAME) expression. */ @SuppressWarnings("unchecked") public void testShneCondition2() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHNE, createNumber(56), createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE))), ImmutableSet.of(new TypedName("a", NUMBER_TYPE))); } /** * Tests reverse interpretation of a SHNE(NAME, NAME) expression. */ @SuppressWarnings("unchecked") public void testShneCondition3() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHNE, createVar(blind, "b", createUnionType(STRING_TYPE, BOOLEAN_TYPE)), createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE)), new TypedName("b", createUnionType(STRING_TYPE, BOOLEAN_TYPE))), ImmutableSet.of(new TypedName("a", STRING_TYPE), new TypedName("b", STRING_TYPE))); } @SuppressWarnings("unchecked") public void testShneCondition4() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHNE, createVar(blind, "a", createUnionType(STRING_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(VOID_TYPE)), ImmutableSet.of(new TypedName("a", STRING_TYPE), new TypedName("b", VOID_TYPE)), ImmutableSet.of(new TypedName("a", VOID_TYPE), new TypedName("b", VOID_TYPE))); } @SuppressWarnings("unchecked") public void testShneCondition5() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHNE, createVar(blind, "a", createUnionType(NULL_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(NULL_TYPE)), ImmutableSet.of(new TypedName("a", VOID_TYPE), new TypedName("b", NULL_TYPE)), ImmutableSet.of(new TypedName("a", NULL_TYPE), new TypedName("b", NULL_TYPE))); } @SuppressWarnings("unchecked") public void testShneCondition6() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.SHNE, createVar(blind, "a", createUnionType(STRING_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(NUMBER_TYPE, VOID_TYPE)), ImmutableSet.of( new TypedName("a", createUnionType(STRING_TYPE, VOID_TYPE)), new TypedName("b", createUnionType(NUMBER_TYPE, VOID_TYPE))), ImmutableSet.of( new TypedName("a", VOID_TYPE), new TypedName("b", VOID_TYPE))); } /** * Tests reverse interpretation of a EQ(NAME, NULL) expression. */ @SuppressWarnings("unchecked") public void testEqCondition1() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.EQ, createVar(blind, "a", createUnionType(BOOLEAN_TYPE, VOID_TYPE)), createNull(), ImmutableSet.of(new TypedName("a", VOID_TYPE)), ImmutableSet.of(new TypedName("a", BOOLEAN_TYPE))); } /** * Tests reverse interpretation of a NE(NULL, NAME) expression. */ @SuppressWarnings("unchecked") public void testEqCondition2() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.NE, createNull(), createVar(blind, "a", createUnionType(BOOLEAN_TYPE, VOID_TYPE)), ImmutableSet.of(new TypedName("a", BOOLEAN_TYPE)), ImmutableSet.of(new TypedName("a", VOID_TYPE))); } /** * Tests reverse interpretation of a EQ(NAME, NULL) expression. */ @SuppressWarnings("unchecked") public void testEqCondition3() throws Exception { FlowScope blind = newScope(); // (number,undefined,null) JSType nullableOptionalNumber = createUnionType(NULL_TYPE, VOID_TYPE, NUMBER_TYPE); // (null,undefined) JSType nullUndefined = createUnionType(VOID_TYPE, NULL_TYPE); testBinop(blind, Token.EQ, createVar(blind, "a", nullableOptionalNumber), createNull(), ImmutableSet.of(new TypedName("a", nullUndefined)), ImmutableSet.of(new TypedName("a", NUMBER_TYPE))); } /** * Tests reverse interpretation of two undefineds. */ @SuppressWarnings("unchecked") public void testEqCondition4() throws Exception { FlowScope blind = newScope(); testBinop(blind, Token.EQ, createVar(blind, "a", VOID_TYPE), createVar(blind, "b", VOID_TYPE), ImmutableSet.of( new TypedName("a", VOID_TYPE), new TypedName("b", VOID_TYPE)), ImmutableSet.of( new TypedName("a", NO_TYPE), new TypedName("b", NO_TYPE))); } /** * Tests reverse interpretation of a COMPARE(NAME, NUMBER) expression, * where COMPARE can be LE, LT, GE or GT. */ @SuppressWarnings("unchecked") public void testInequalitiesCondition1() { for (Token op : Arrays.asList(Token.LT, Token.GT, Token.LE, Token.GE)) { FlowScope blind = newScope(); testBinop(blind, op, createVar(blind, "a", createUnionType(STRING_TYPE, VOID_TYPE)), createNumber(8), ImmutableSet.of( new TypedName("a", STRING_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, VOID_TYPE)))); } } /** * Tests reverse interpretation of a COMPARE(NAME, NAME) expression, * where COMPARE can be LE, LT, GE or GT. */ @SuppressWarnings("unchecked") public void testInequalitiesCondition2() { for (Token op : Arrays.asList(Token.LT, Token.GT, Token.LE, Token.GE)) { FlowScope blind = newScope(); testBinop(blind, op, createVar(blind, "a", createUnionType(STRING_TYPE, NUMBER_TYPE, VOID_TYPE)), createVar(blind, "b", createUnionType(NUMBER_TYPE, NULL_TYPE)), ImmutableSet.of( new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE)), new TypedName("b", createUnionType(NUMBER_TYPE, NULL_TYPE))), ImmutableSet.of( new TypedName("a", createUnionType(STRING_TYPE, NUMBER_TYPE, VOID_TYPE)), new TypedName("b", createUnionType(NUMBER_TYPE, NULL_TYPE)))); } } /** * Tests reverse interpretation of a COMPARE(NUMBER-untyped, NAME) expression, * where COMPARE can be LE, LT, GE or GT. */ @SuppressWarnings("unchecked") public void testInequalitiesCondition3() { for (Token op : Arrays.asList(Token.LT, Token.GT, Token.LE, Token.GE)) { FlowScope blind = newScope(); testBinop(blind, op, createUntypedNumber(8), createVar(blind, "a", createUnionType(STRING_TYPE, VOID_TYPE)), ImmutableSet.of( new TypedName("a", STRING_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(STRING_TYPE, VOID_TYPE)))); } } @SuppressWarnings("unchecked") public void testAnd() { FlowScope blind = newScope(); testBinop(blind, Token.AND, createVar(blind, "b", createUnionType(STRING_TYPE, NULL_TYPE)), createVar(blind, "a", createUnionType(NUMBER_TYPE, VOID_TYPE)), ImmutableSet.of(new TypedName("a", NUMBER_TYPE), new TypedName("b", STRING_TYPE)), ImmutableSet.of(new TypedName("a", createUnionType(NUMBER_TYPE, VOID_TYPE)), new TypedName("b", createUnionType(STRING_TYPE, NULL_TYPE)))); } @SuppressWarnings("unchecked") public void testTypeof1() { FlowScope blind = newScope(); testBinop(blind, Token.EQ, new Node(Token.TYPEOF, createVar(blind, "a", OBJECT_TYPE)), Node.newString("function"), ImmutableSet.of( new TypedName("a", U2U_CONSTRUCTOR_TYPE)), ImmutableSet.of( new TypedName("a", OBJECT_TYPE))); } @SuppressWarnings("unchecked") public void testTypeof2() { FlowScope blind = newScope(); testBinop(blind, Token.EQ, new Node(Token.TYPEOF, createVar(blind, "a", ALL_TYPE)), Node.newString("function"), ImmutableSet.of( new TypedName("a", U2U_CONSTRUCTOR_TYPE)), ImmutableSet.of( new TypedName("a", ALL_TYPE))); } @SuppressWarnings("unchecked") public void testTypeof3() { FlowScope blind = newScope(); testBinop(blind, Token.EQ, new Node(Token.TYPEOF, createVar( blind, "a", OBJECT_NUMBER_STRING_BOOLEAN)), Node.newString("function"), ImmutableSet.of( new TypedName("a", U2U_CONSTRUCTOR_TYPE)), ImmutableSet.of( new TypedName("a", OBJECT_NUMBER_STRING_BOOLEAN))); } @SuppressWarnings("unchecked") public void testTypeof4() { FlowScope blind = newScope(); testBinop(blind, Token.EQ, new Node(Token.TYPEOF, createVar( blind, "a", createUnionType( U2U_CONSTRUCTOR_TYPE, NUMBER_STRING_BOOLEAN))), Node.newString("function"), ImmutableSet.of( new TypedName("a", U2U_CONSTRUCTOR_TYPE)), ImmutableSet.of( new TypedName("a", NUMBER_STRING_BOOLEAN))); } @SuppressWarnings("unchecked") public void testInstanceOf() { FlowScope blind = newScope(); testBinop(blind, Token.INSTANCEOF, createVar(blind, "x", UNKNOWN_TYPE), createVar(blind, "s", STRING_OBJECT_FUNCTION_TYPE), ImmutableSet.of( new TypedName("x", STRING_OBJECT_TYPE), new TypedName("s", STRING_OBJECT_FUNCTION_TYPE)), ImmutableSet.of( new TypedName("s", STRING_OBJECT_FUNCTION_TYPE))); } @SuppressWarnings("unchecked") public void testInstanceOf2() { FlowScope blind = newScope(); testBinop(blind, Token.INSTANCEOF, createVar(blind, "x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE)), createVar(blind, "s", STRING_OBJECT_FUNCTION_TYPE), ImmutableSet.of( new TypedName("x", STRING_OBJECT_TYPE), new TypedName("s", STRING_OBJECT_FUNCTION_TYPE)), ImmutableSet.of( new TypedName("x", NUMBER_OBJECT_TYPE), new TypedName("s", STRING_OBJECT_FUNCTION_TYPE))); } @SuppressWarnings("unchecked") public void testInstanceOf3() { FlowScope blind = newScope(); testBinop(blind, Token.INSTANCEOF, createVar(blind, "x", OBJECT_TYPE), createVar(blind, "s", STRING_OBJECT_FUNCTION_TYPE), ImmutableSet.of( new TypedName("x", STRING_OBJECT_TYPE), new TypedName("s", STRING_OBJECT_FUNCTION_TYPE)), ImmutableSet.of( new TypedName("x", OBJECT_TYPE), new TypedName("s", STRING_OBJECT_FUNCTION_TYPE))); } @SuppressWarnings("unchecked") public void testInstanceOf4() { FlowScope blind = newScope(); testBinop(blind, Token.INSTANCEOF, createVar(blind, "x", ALL_TYPE), createVar(blind, "s", STRING_OBJECT_FUNCTION_TYPE), ImmutableSet.of( new TypedName("x", STRING_OBJECT_TYPE), new TypedName("s", STRING_OBJECT_FUNCTION_TYPE)), ImmutableSet.of( new TypedName("s", STRING_OBJECT_FUNCTION_TYPE))); } private void testBinop(FlowScope blind, Token binop, Node left, Node right, Collection<TypedName> trueOutcome, Collection<TypedName> falseOutcome) { Node condition = new Node(binop); condition.addChildToBack(left); condition.addChildToBack(right); // true outcome. FlowScope informedTrue = interpreter. getPreciserScopeKnowingConditionOutcome(condition, blind, true); for (TypedName p : trueOutcome) { assertTypeEquals(p.name, p.type, getVarType(informedTrue, p.name)); } // false outcome. FlowScope informedFalse = interpreter. getPreciserScopeKnowingConditionOutcome(condition, blind, false); for (TypedName p : falseOutcome) { assertTypeEquals(p.type, getVarType(informedFalse, p.name)); } } private Node createNull() { Node n = new Node(Token.NULL); n.setJSType(NULL_TYPE); return n; } private Node createNumber(int n) { Node number = createUntypedNumber(n); number.setJSType(NUMBER_TYPE); return number; } private Node createUntypedNumber(int n) { return Node.newNumber(n); } private JSType getVarType(FlowScope scope, String name) { return scope.getSlot(name).getType(); } private Node createVar(FlowScope scope, String name, JSType type) { Node n = Node.newString(Token.NAME, name); functionScope.declare(name, n, null, null); scope.inferSlotType(name, type); n.setJSType(type); return n; } private static class TypedName { private final String name; private final JSType type; private TypedName(String name, JSType type) { this.name = name; this.type = type; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.Set; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.BatchScanner; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.core.security.SystemPermission; import org.apache.accumulo.core.security.TablePermission; import org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl; import org.apache.accumulo.server.security.AuditedSecurityOperation; import org.apache.accumulo.test.functional.ConfigurableMacIT; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.hadoop.io.Text; import org.junit.Before; import org.junit.Test; /** * Tests that Accumulo is outputting audit messages as expected. Since this is using MiniAccumuloCluster, it could take a while if we test everything in * isolation. We test blocks of related operations, run the whole test in one MiniAccumulo instance, trying to clean up objects between each test. The * MiniAccumuloClusterTest sets up the log4j stuff differently to an installed instance, instead piping everything through stdout and writing to a set location * so we have to find the logs and grep the bits we need out. */ public class AuditMessageIT extends ConfigurableMacIT { private static final String AUDIT_USER_1 = "AuditUser1"; private static final String AUDIT_USER_2 = "AuditUser2"; private static final String PASSWORD = "password"; private static final String OLD_TEST_TABLE_NAME = "apples"; private static final String NEW_TEST_TABLE_NAME = "oranges"; private static final String THIRD_TEST_TABLE_NAME = "pears"; private static final Authorizations auths = new Authorizations("private", "public"); // Must be static to survive Junit re-initialising the class every time. private static String lastAuditTimestamp; private Connector auditConnector; private Connector conn; private static ArrayList<String> findAuditMessage(ArrayList<String> input, String pattern) { ArrayList<String> result = new ArrayList<String>(); for (String s : input) { if (s.matches(".*" + pattern + ".*")) result.add(s); } return result; } /** * Returns a List of Audit messages that have been grep'd out of the MiniAccumuloCluster output. * * @param stepName * A unique name for the test being executed, to identify the System.out messages. * @return A List of the Audit messages, sorted (so in chronological order). */ private ArrayList<String> getAuditMessages(String stepName) throws IOException { for (MiniAccumuloClusterImpl.LogWriter lw : getCluster().getLogWriters()) { lw.flush(); } // Grab the audit messages System.out.println("Start of captured audit messages for step " + stepName); ArrayList<String> result = new ArrayList<String>(); for (File file : getCluster().getConfig().getLogDir().listFiles()) { // We want to grab the files called .out if (file.getName().contains(".out") && file.isFile() && file.canRead()) { LineIterator it = FileUtils.lineIterator(file, StandardCharsets.UTF_8.name()); try { while (it.hasNext()) { String line = it.nextLine(); if (line.matches(".* \\[" + AuditedSecurityOperation.AUDITLOG + "\\s*\\].*")) { // Only include the message if startTimestamp is null. or the message occurred after the startTimestamp value if ((lastAuditTimestamp == null) || (line.substring(0, 23).compareTo(lastAuditTimestamp) > 0)) result.add(line); } } } finally { LineIterator.closeQuietly(it); } } } Collections.sort(result); for (String s : result) { System.out.println(s); } System.out.println("End of captured audit messages for step " + stepName); if (result.size() > 0) lastAuditTimestamp = (result.get(result.size() - 1)).substring(0, 23); return result; } private void grantEverySystemPriv(Connector conn, String user) throws AccumuloSecurityException, AccumuloException { SystemPermission[] arrayOfP = new SystemPermission[] {SystemPermission.SYSTEM, SystemPermission.ALTER_TABLE, SystemPermission.ALTER_USER, SystemPermission.CREATE_TABLE, SystemPermission.CREATE_USER, SystemPermission.DROP_TABLE, SystemPermission.DROP_USER}; for (SystemPermission p : arrayOfP) { conn.securityOperations().grantSystemPermission(user, p); } } @Before public void resetInstance() throws AccumuloException, AccumuloSecurityException, TableNotFoundException, IOException { conn = getConnector(); // I don't want to recreate the instance for every test since it will take ages. // If we run every test as non-root users, I can drop these users every test which should effectively // reset the environment. if (conn.securityOperations().listLocalUsers().contains(AUDIT_USER_1)) conn.securityOperations().dropLocalUser(AUDIT_USER_1); if (conn.securityOperations().listLocalUsers().contains(AUDIT_USER_2)) conn.securityOperations().dropLocalUser(AUDIT_USER_2); if (conn.securityOperations().listLocalUsers().contains(AUDIT_USER_2)) conn.securityOperations().dropLocalUser(THIRD_TEST_TABLE_NAME); if (conn.tableOperations().exists(NEW_TEST_TABLE_NAME)) conn.tableOperations().delete(NEW_TEST_TABLE_NAME); if (conn.tableOperations().exists(OLD_TEST_TABLE_NAME)) conn.tableOperations().delete(OLD_TEST_TABLE_NAME); // This will set the lastAuditTimestamp for the first test getAuditMessages("setup"); } @Test(timeout = 60 * 1000) public void testTableOperationsAudits() throws AccumuloException, AccumuloSecurityException, TableExistsException, TableNotFoundException, IOException, InterruptedException { conn.securityOperations().createLocalUser(AUDIT_USER_1, new PasswordToken(PASSWORD)); conn.securityOperations().grantSystemPermission(AUDIT_USER_1, SystemPermission.SYSTEM); conn.securityOperations().grantSystemPermission(AUDIT_USER_1, SystemPermission.CREATE_TABLE); // Connect as Audit User and do a bunch of stuff. // Testing activity begins here auditConnector = getCluster().getConnector(AUDIT_USER_1, PASSWORD); auditConnector.tableOperations().create(OLD_TEST_TABLE_NAME); auditConnector.tableOperations().rename(OLD_TEST_TABLE_NAME, NEW_TEST_TABLE_NAME); Map<String,String> emptyMap = Collections.emptyMap(); Set<String> emptySet = Collections.emptySet(); auditConnector.tableOperations().clone(NEW_TEST_TABLE_NAME, OLD_TEST_TABLE_NAME, true, emptyMap, emptySet); auditConnector.tableOperations().delete(OLD_TEST_TABLE_NAME); auditConnector.tableOperations().offline(NEW_TEST_TABLE_NAME); auditConnector.tableOperations().delete(NEW_TEST_TABLE_NAME); // Testing activity ends here ArrayList<String> auditMessages = getAuditMessages("testTableOperationsAudits"); assertEquals(1, findAuditMessage(auditMessages, "action: createTable; targetTable: " + OLD_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, "action: renameTable; targetTable: " + OLD_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, "action: cloneTable; targetTable: " + NEW_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, "action: deleteTable; targetTable: " + OLD_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, "action: offlineTable; targetTable: " + NEW_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, "action: deleteTable; targetTable: " + NEW_TEST_TABLE_NAME).size()); } @Test(timeout = 60 * 1000) public void testUserOperationsAudits() throws AccumuloSecurityException, AccumuloException, TableExistsException, InterruptedException, IOException { conn.securityOperations().createLocalUser(AUDIT_USER_1, new PasswordToken(PASSWORD)); conn.securityOperations().grantSystemPermission(AUDIT_USER_1, SystemPermission.SYSTEM); conn.securityOperations().grantSystemPermission(AUDIT_USER_1, SystemPermission.CREATE_USER); grantEverySystemPriv(conn, AUDIT_USER_1); // Connect as Audit User and do a bunch of stuff. // Start testing activities here auditConnector = getCluster().getConnector(AUDIT_USER_1, PASSWORD); auditConnector.securityOperations().createLocalUser(AUDIT_USER_2, new PasswordToken(PASSWORD)); // It seems only root can grant stuff. conn.securityOperations().grantSystemPermission(AUDIT_USER_2, SystemPermission.ALTER_TABLE); conn.securityOperations().revokeSystemPermission(AUDIT_USER_2, SystemPermission.ALTER_TABLE); auditConnector.tableOperations().create(NEW_TEST_TABLE_NAME); conn.securityOperations().grantTablePermission(AUDIT_USER_2, NEW_TEST_TABLE_NAME, TablePermission.READ); conn.securityOperations().revokeTablePermission(AUDIT_USER_2, NEW_TEST_TABLE_NAME, TablePermission.READ); auditConnector.securityOperations().changeLocalUserPassword(AUDIT_USER_2, new PasswordToken("anything")); auditConnector.securityOperations().changeUserAuthorizations(AUDIT_USER_2, auths); auditConnector.securityOperations().dropLocalUser(AUDIT_USER_2); // Stop testing activities here ArrayList<String> auditMessages = getAuditMessages("testUserOperationsAudits"); assertEquals(1, findAuditMessage(auditMessages, "action: createUser; targetUser: " + AUDIT_USER_2).size()); assertEquals( 1, findAuditMessage(auditMessages, "action: grantSystemPermission; permission: " + SystemPermission.ALTER_TABLE.toString() + "; targetUser: " + AUDIT_USER_2).size()); assertEquals( 1, findAuditMessage(auditMessages, "action: revokeSystemPermission; permission: " + SystemPermission.ALTER_TABLE.toString() + "; targetUser: " + AUDIT_USER_2).size()); assertEquals( 1, findAuditMessage(auditMessages, "action: grantTablePermission; permission: " + TablePermission.READ.toString() + "; targetTable: " + NEW_TEST_TABLE_NAME).size()); assertEquals( 1, findAuditMessage(auditMessages, "action: revokeTablePermission; permission: " + TablePermission.READ.toString() + "; targetTable: " + NEW_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, "action: changePassword; targetUser: " + AUDIT_USER_2 + "").size()); assertEquals(1, findAuditMessage(auditMessages, "action: changeAuthorizations; targetUser: " + AUDIT_USER_2 + "; authorizations: " + auths.toString()) .size()); assertEquals(1, findAuditMessage(auditMessages, "action: dropUser; targetUser: " + AUDIT_USER_2).size()); } @Test(timeout = 60 * 1000) public void testImportExportOperationsAudits() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException, IOException, InterruptedException { conn.securityOperations().createLocalUser(AUDIT_USER_1, new PasswordToken(PASSWORD)); conn.securityOperations().grantSystemPermission(AUDIT_USER_1, SystemPermission.SYSTEM); conn.securityOperations().changeUserAuthorizations(AUDIT_USER_1, auths); grantEverySystemPriv(conn, AUDIT_USER_1); // Connect as Audit User and do a bunch of stuff. // Start testing activities here auditConnector = getCluster().getConnector(AUDIT_USER_1, PASSWORD); auditConnector.tableOperations().create(OLD_TEST_TABLE_NAME); // Insert some play data BatchWriter bw = auditConnector.createBatchWriter(OLD_TEST_TABLE_NAME, new BatchWriterConfig()); Mutation m = new Mutation("myRow"); m.put("cf1", "cq1", "v1"); m.put("cf1", "cq2", "v3"); bw.addMutation(m); bw.close(); // Prepare to export the table File exportDir = new File(getCluster().getConfig().getDir().toString() + "/export"); auditConnector.tableOperations().offline(OLD_TEST_TABLE_NAME); auditConnector.tableOperations().exportTable(OLD_TEST_TABLE_NAME, exportDir.toString()); // We've exported the table metadata to the MiniAccumuloCluster root dir. Grab the .rf file path to re-import it File distCpTxt = new File(exportDir.toString() + "/distcp.txt"); File importFile = null; LineIterator it = FileUtils.lineIterator(distCpTxt, StandardCharsets.UTF_8.name()); // Just grab the first rf file, it will do for now. String filePrefix = "file:"; try { while (it.hasNext() && importFile == null) { String line = it.nextLine(); if (line.matches(".*\\.rf")) { importFile = new File(line.replaceFirst(filePrefix, "")); } } } finally { LineIterator.closeQuietly(it); } FileUtils.copyFileToDirectory(importFile, exportDir); auditConnector.tableOperations().importTable(NEW_TEST_TABLE_NAME, exportDir.toString()); // Now do a Directory (bulk) import of the same data. auditConnector.tableOperations().create(THIRD_TEST_TABLE_NAME); File failDir = new File(exportDir + "/tmp"); failDir.mkdirs(); auditConnector.tableOperations().importDirectory(THIRD_TEST_TABLE_NAME, exportDir.toString(), failDir.toString(), false); auditConnector.tableOperations().online(OLD_TEST_TABLE_NAME); // Stop testing activities here ArrayList<String> auditMessages = getAuditMessages("testImportExportOperationsAudits"); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_CREATE_TABLE_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME)).size()); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_ONLINE_OFFLINE_TABLE_AUDIT_TEMPLATE, "offlineTable", OLD_TEST_TABLE_NAME)) .size()); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_EXPORT_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME, exportDir.toString())).size()); assertEquals( 1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_IMPORT_AUDIT_TEMPLATE, NEW_TEST_TABLE_NAME, filePrefix + exportDir.toString())).size()); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_CREATE_TABLE_AUDIT_TEMPLATE, THIRD_TEST_TABLE_NAME)).size()); assertEquals( 1, findAuditMessage( auditMessages, String.format(AuditedSecurityOperation.CAN_BULK_IMPORT_AUDIT_TEMPLATE, THIRD_TEST_TABLE_NAME, filePrefix + exportDir.toString(), filePrefix + failDir.toString())).size()); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_ONLINE_OFFLINE_TABLE_AUDIT_TEMPLATE, "onlineTable", OLD_TEST_TABLE_NAME)) .size()); } @Test(timeout = 60 * 1000) public void testDataOperationsAudits() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException, IOException, InterruptedException { conn.securityOperations().createLocalUser(AUDIT_USER_1, new PasswordToken(PASSWORD)); conn.securityOperations().grantSystemPermission(AUDIT_USER_1, SystemPermission.SYSTEM); conn.securityOperations().changeUserAuthorizations(AUDIT_USER_1, auths); grantEverySystemPriv(conn, AUDIT_USER_1); // Connect as Audit User and do a bunch of stuff. // Start testing activities here auditConnector = getCluster().getConnector(AUDIT_USER_1, PASSWORD); auditConnector.tableOperations().create(OLD_TEST_TABLE_NAME); // Insert some play data BatchWriter bw = auditConnector.createBatchWriter(OLD_TEST_TABLE_NAME, new BatchWriterConfig()); Mutation m = new Mutation("myRow"); m.put("cf1", "cq1", "v1"); m.put("cf1", "cq2", "v3"); bw.addMutation(m); bw.close(); // Start testing activities here // A regular scan Scanner scanner = auditConnector.createScanner(OLD_TEST_TABLE_NAME, auths); for (Map.Entry<Key,Value> entry : scanner) { System.out.println("Scanner row: " + entry.getKey() + " " + entry.getValue()); } scanner.close(); // A batch scan BatchScanner bs = auditConnector.createBatchScanner(OLD_TEST_TABLE_NAME, auths, 1); bs.fetchColumn(new Text("cf1"), new Text("cq1")); bs.setRanges(Arrays.asList(new Range("myRow", "myRow~"))); for (Map.Entry<Key,Value> entry : bs) { System.out.println("BatchScanner row: " + entry.getKey() + " " + entry.getValue()); } bs.close(); // Delete some data. auditConnector.tableOperations().deleteRows(OLD_TEST_TABLE_NAME, new Text("myRow"), new Text("myRow~")); // End of testing activities ArrayList<String> auditMessages = getAuditMessages("testDataOperationsAudits"); assertTrue(1 <= findAuditMessage(auditMessages, "action: scan; targetTable: " + OLD_TEST_TABLE_NAME).size()); assertTrue(1 <= findAuditMessage(auditMessages, "action: scan; targetTable: " + OLD_TEST_TABLE_NAME).size()); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CAN_DELETE_RANGE_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME, "myRow", "myRow~")).size()); } @Test(timeout = 60 * 1000) public void testDeniedAudits() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException, IOException, InterruptedException { // Create our user with no privs conn.securityOperations().createLocalUser(AUDIT_USER_1, new PasswordToken(PASSWORD)); conn.tableOperations().create(OLD_TEST_TABLE_NAME); auditConnector = getCluster().getConnector(AUDIT_USER_1, PASSWORD); // Start testing activities // We should get denied or / failed audit messages here. // We don't want the thrown exceptions to stop our tests, and we are not testing that the Exceptions are thrown. try { auditConnector.tableOperations().create(NEW_TEST_TABLE_NAME); } catch (AccumuloSecurityException ex) {} try { auditConnector.tableOperations().rename(OLD_TEST_TABLE_NAME, NEW_TEST_TABLE_NAME); } catch (AccumuloSecurityException ex) {} try { auditConnector.tableOperations().clone(OLD_TEST_TABLE_NAME, NEW_TEST_TABLE_NAME, true, Collections.<String,String> emptyMap(), Collections.<String> emptySet()); } catch (AccumuloSecurityException ex) {} try { auditConnector.tableOperations().delete(OLD_TEST_TABLE_NAME); } catch (AccumuloSecurityException ex) {} try { auditConnector.tableOperations().offline(OLD_TEST_TABLE_NAME); } catch (AccumuloSecurityException ex) {} try { Scanner scanner = auditConnector.createScanner(OLD_TEST_TABLE_NAME, auths); scanner.iterator().next().getKey(); } catch (RuntimeException ex) {} try { auditConnector.tableOperations().deleteRows(OLD_TEST_TABLE_NAME, new Text("myRow"), new Text("myRow~")); } catch (AccumuloSecurityException ex) {} // ... that will do for now. // End of testing activities ArrayList<String> auditMessages = getAuditMessages("testDeniedAudits"); assertEquals(1, findAuditMessage(auditMessages, "operation: denied;.*" + String.format(AuditedSecurityOperation.CAN_CREATE_TABLE_AUDIT_TEMPLATE, NEW_TEST_TABLE_NAME)) .size()); assertEquals( 1, findAuditMessage(auditMessages, "operation: denied;.*" + String.format(AuditedSecurityOperation.CAN_RENAME_TABLE_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME, NEW_TEST_TABLE_NAME)).size()); assertEquals( 1, findAuditMessage(auditMessages, "operation: denied;.*" + String.format(AuditedSecurityOperation.CAN_CLONE_TABLE_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME, NEW_TEST_TABLE_NAME)).size()); assertEquals(1, findAuditMessage(auditMessages, "operation: denied;.*" + String.format(AuditedSecurityOperation.CAN_DELETE_TABLE_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME)) .size()); assertEquals( 1, findAuditMessage(auditMessages, "operation: denied;.*" + String.format(AuditedSecurityOperation.CAN_ONLINE_OFFLINE_TABLE_AUDIT_TEMPLATE, "offlineTable", OLD_TEST_TABLE_NAME)) .size()); assertEquals(1, findAuditMessage(auditMessages, "operation: denied;.*" + "action: scan; targetTable: " + OLD_TEST_TABLE_NAME).size()); assertEquals( 1, findAuditMessage(auditMessages, "operation: denied;.*" + String.format(AuditedSecurityOperation.CAN_DELETE_RANGE_AUDIT_TEMPLATE, OLD_TEST_TABLE_NAME, "myRow", "myRow~")).size()); } @Test(timeout = 60 * 1000) public void testFailedAudits() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException, IOException, InterruptedException { // Start testing activities // Test that we get a few "failed" audit messages come through when we tell it to do dumb stuff // We don't want the thrown exceptions to stop our tests, and we are not testing that the Exceptions are thrown. try { conn.securityOperations().dropLocalUser(AUDIT_USER_2); } catch (AccumuloSecurityException ex) {} try { conn.securityOperations().revokeSystemPermission(AUDIT_USER_2, SystemPermission.ALTER_TABLE); } catch (AccumuloSecurityException ex) {} try { conn.securityOperations().createLocalUser("root", new PasswordToken("super secret")); } catch (AccumuloSecurityException ex) {} ArrayList<String> auditMessages = getAuditMessages("testFailedAudits"); // ... that will do for now. // End of testing activities assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.DROP_USER_AUDIT_TEMPLATE, AUDIT_USER_2)).size()); assertEquals( 1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.REVOKE_SYSTEM_PERMISSION_AUDIT_TEMPLATE, SystemPermission.ALTER_TABLE, AUDIT_USER_2)).size()); assertEquals(1, findAuditMessage(auditMessages, String.format(AuditedSecurityOperation.CREATE_USER_AUDIT_TEMPLATE, "root", "")).size()); } }
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.builder; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import org.gradle.api.artifacts.VersionConstraint; import org.gradle.api.artifacts.component.ComponentIdentifier; import org.gradle.api.artifacts.component.ComponentSelector; import org.gradle.api.artifacts.component.ModuleComponentIdentifier; import org.gradle.api.artifacts.component.ModuleComponentSelector; import org.gradle.api.internal.attributes.AttributesSchemaInternal; import org.gradle.api.internal.attributes.ImmutableAttributes; import org.gradle.internal.component.external.model.DefaultConfigurationMetadata; import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier; import org.gradle.internal.component.external.model.DefaultModuleComponentSelector; import org.gradle.internal.component.external.model.ModuleComponentArtifactMetadata; import org.gradle.internal.component.external.model.ModuleDependencyMetadata; import org.gradle.internal.component.external.model.VariantMetadataRules; import org.gradle.internal.component.model.ComponentResolveMetadata; import org.gradle.internal.component.model.ConfigurationMetadata; import org.gradle.internal.component.model.DependencyMetadata; import org.gradle.internal.component.model.ExcludeMetadata; import org.gradle.internal.component.model.ForcingDependencyMetadata; import org.gradle.internal.component.model.IvyArtifactName; import org.gradle.internal.component.model.LocalComponentDependencyMetadata; import java.util.Collections; import java.util.List; import java.util.Set; class LenientPlatformDependencyMetadata implements ModuleDependencyMetadata, ForcingDependencyMetadata { private final ResolveState resolveState; private final NodeState from; private final ModuleComponentSelector cs; private final ModuleComponentIdentifier componentId; private final ComponentIdentifier platformId; // just for reporting private final boolean force; private final boolean transitive; LenientPlatformDependencyMetadata(ResolveState resolveState, NodeState from, ModuleComponentSelector cs, ModuleComponentIdentifier componentId, ComponentIdentifier platformId, boolean force, boolean transitive) { this.resolveState = resolveState; this.from = from; this.cs = cs; this.componentId = componentId; this.platformId = platformId; this.force = force; this.transitive = transitive; } @Override public ModuleComponentSelector getSelector() { return cs; } @Override public ModuleDependencyMetadata withRequestedVersion(VersionConstraint requestedVersion) { return this; } @Override public ModuleDependencyMetadata withReason(String reason) { return this; } @Override public List<ConfigurationMetadata> selectConfigurations(ImmutableAttributes consumerAttributes, ComponentResolveMetadata targetComponent, AttributesSchemaInternal consumerSchema) { if (targetComponent instanceof LenientPlatformResolveMetadata) { LenientPlatformResolveMetadata platformMetadata = (LenientPlatformResolveMetadata) targetComponent; return Collections.<ConfigurationMetadata>singletonList(new LenientPlatformConfigurationMetadata(platformMetadata.getPlatformState(), platformId)); } // the target component exists, so we need to fallback to the traditional selection process return new LocalComponentDependencyMetadata(componentId, cs, null, ImmutableAttributes.EMPTY, ImmutableAttributes.EMPTY, null, Collections.<IvyArtifactName>emptyList(), Collections.<ExcludeMetadata>emptyList(), false, false, true, false, null).selectConfigurations(consumerAttributes, targetComponent, consumerSchema); } @Override public List<ExcludeMetadata> getExcludes() { return Collections.emptyList(); } @Override public List<IvyArtifactName> getArtifacts() { return Collections.emptyList(); } @Override public DependencyMetadata withTarget(ComponentSelector target) { return this; } @Override public boolean isChanging() { return false; } @Override public boolean isTransitive() { return transitive; } @Override public boolean isConstraint() { return true; } @Override public String getReason() { return "belongs to platform " + platformId; } @Override public String toString() { return "virtual metadata for " + componentId; } @Override public boolean isForce() { return force; } @Override public ForcingDependencyMetadata forced() { return new LenientPlatformDependencyMetadata(resolveState, from, cs, componentId, platformId, true, transitive); } private class LenientPlatformConfigurationMetadata extends DefaultConfigurationMetadata implements ConfigurationMetadata { private final VirtualPlatformState platformState; private final ComponentIdentifier platformId; public LenientPlatformConfigurationMetadata(VirtualPlatformState platform, ComponentIdentifier platformId) { super(componentId, "default", true, false, ImmutableSet.of("default"), ImmutableList.<ModuleComponentArtifactMetadata>of(), VariantMetadataRules.noOp(), ImmutableList.<ExcludeMetadata>of(), ImmutableAttributes.EMPTY); this.platformState = platform; this.platformId = platformId; } @Override public List<? extends DependencyMetadata> getDependencies() { List<DependencyMetadata> result = null; List<String> candidateVersions = platformState.getCandidateVersions(); Set<ModuleResolveState> modules = platformState.getParticipatingModules(); for (ModuleResolveState module : modules) { ComponentState selected = module.getSelected(); if (selected != null) { String componentVersion = selected.getId().getVersion(); for (String target : candidateVersions) { ModuleComponentIdentifier leafId = DefaultModuleComponentIdentifier.newId(module.getId(), target); ModuleComponentSelector leafSelector = DefaultModuleComponentSelector.newSelector(module.getId(), target); ComponentIdentifier platformId = platformState.getSelectedPlatformId(); if (platformId == null) { // Not sure this can happen, unless in error state platformId = this.platformId; } if (!componentVersion.equals(target)) { // We will only add dependencies to the leaves if there is such a published module PotentialEdge potentialEdge = PotentialEdge.of(resolveState, from, leafId, leafSelector, platformId, platformState.isForced(), false); if (potentialEdge.metadata != null) { result = registerPlatformEdge(result, modules, leafId, leafSelector, platformId, platformState.isForced()); break; } } else { // at this point we know the component exists result = registerPlatformEdge(result, modules, leafId, leafSelector, platformId, platformState.isForced()); break; } } platformState.attachOrphanEdges(); } } return result == null ? Collections.<DependencyMetadata>emptyList() : result; } private List<DependencyMetadata> registerPlatformEdge(List<DependencyMetadata> result, Set<ModuleResolveState> modules, ModuleComponentIdentifier leafId, ModuleComponentSelector leafSelector, ComponentIdentifier platformId, boolean force) { if (result == null) { result = Lists.newArrayListWithExpectedSize(modules.size()); } result.add(new LenientPlatformDependencyMetadata( resolveState, from, leafSelector, leafId, platformId, force, false )); return result; } } }
/* * Copyright (C) 2015 Willi Ye * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.grarak.kerneladiutor.fragments.kernel; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.View; import com.grarak.kerneladiutor.R; import com.grarak.kerneladiutor.elements.ColorPalette; import com.grarak.kerneladiutor.elements.DAdapter; import com.grarak.kerneladiutor.elements.DDivider; import com.grarak.kerneladiutor.elements.cards.CardViewItem; import com.grarak.kerneladiutor.elements.cards.EditTextCardView; import com.grarak.kerneladiutor.elements.cards.PopupCardView; import com.grarak.kerneladiutor.elements.cards.SeekBarCardView; import com.grarak.kerneladiutor.elements.cards.SwitchCardView; import com.grarak.kerneladiutor.fragments.RecyclerViewFragment; import com.grarak.kerneladiutor.utils.Constants; import com.grarak.kerneladiutor.utils.Utils; import com.grarak.kerneladiutor.utils.WebpageReader; import com.grarak.kerneladiutor.utils.json.GammaProfiles; import com.grarak.kerneladiutor.utils.kernel.Screen; import com.kerneladiutor.library.Tools; import java.util.ArrayList; import java.util.List; /** * Created by willi on 26.12.14. */ public class ScreenFragment extends RecyclerViewFragment implements SeekBarCardView.DSeekBarCard.OnDSeekBarCardListener, SwitchCardView.DSwitchCard.OnDSwitchCardListener, EditTextCardView.DEditTextCard.OnDEditTextCardListener, PopupCardView.DPopupCard.OnDPopupCardListener, CardViewItem.DCardView.OnDCardListener { private ColorPalette mColorPalette; private List<String> mColorCalibrationLimits; private SeekBarCardView.DSeekBarCard[] mColorCalibrationCard; private SeekBarCardView.DSeekBarCard mColorCalibrationMinCard; private SwitchCardView.DSwitchCard mInvertScreenCard; private SeekBarCardView.DSeekBarCard mSaturationIntensityCard; private SwitchCardView.DSwitchCard mGrayscaleModeCard; private SeekBarCardView.DSeekBarCard mScreenHueCard; private SeekBarCardView.DSeekBarCard mScreenValueCard; private SeekBarCardView.DSeekBarCard mScreenContrastCard; private SwitchCardView.DSwitchCard mScreenHBMCard; private SwitchCardView.DSwitchCard mScreenColorTempEnableCard; private EditTextCardView.DEditTextCard mKGammaBlueCard; private EditTextCardView.DEditTextCard mKGammaGreenCard; private EditTextCardView.DEditTextCard mKGammaRedCard; private PopupCardView.DPopupCard mKGammaProfilesCard; private EditTextCardView.DEditTextCard mGammaControlRedGreysCard; private EditTextCardView.DEditTextCard mGammaControlRedMidsCard; private EditTextCardView.DEditTextCard mGammaControlRedBlacksCard; private EditTextCardView.DEditTextCard mGammaControlRedWhitesCard; private EditTextCardView.DEditTextCard mGammaControlGreenGreysCard; private EditTextCardView.DEditTextCard mGammaControlGreenMidsCard; private EditTextCardView.DEditTextCard mGammaControlGreenBlacksCard; private EditTextCardView.DEditTextCard mGammaControlGreenWhitesCard; private EditTextCardView.DEditTextCard mGammaControlBlueGreysCard; private EditTextCardView.DEditTextCard mGammaControlBlueMidsCard; private EditTextCardView.DEditTextCard mGammaControlBlueBlacksCard; private EditTextCardView.DEditTextCard mGammaControlBlueWhitesCard; private EditTextCardView.DEditTextCard mGammaControlContrastCard; private EditTextCardView.DEditTextCard mGammaControlBrightnessCard; private EditTextCardView.DEditTextCard mGammaControlSaturationCard; private PopupCardView.DPopupCard mGammaControlProfilesCard; private EditTextCardView.DEditTextCard mDsiPanelBlueNegativeCard; private EditTextCardView.DEditTextCard mDsiPanelBluePositiveCard; private EditTextCardView.DEditTextCard mDsiPanelGreenNegativeCard; private EditTextCardView.DEditTextCard mDsiPanelGreenPositiveCard; private EditTextCardView.DEditTextCard mDsiPanelRedNegativeCard; private EditTextCardView.DEditTextCard mDsiPanelRedPositiveCard; private EditTextCardView.DEditTextCard mDsiPanelWhitePointCard; private PopupCardView.DPopupCard mDsiPanelProfilesCard; private CardViewItem.DCardView mAdditionalProfilesCard; private SwitchCardView.DSwitchCard mBrightnessModeCard; private SeekBarCardView.DSeekBarCard mLcdMinBrightnessCard; private SeekBarCardView.DSeekBarCard mLcdMaxBrightnessCard; private SwitchCardView.DSwitchCard mBackLightDimmerEnableCard; private SeekBarCardView.DSeekBarCard mBackLightDimmerMinBrightnessCard; private SeekBarCardView.DSeekBarCard mBackLightDimmerThresholdCard; private SeekBarCardView.DSeekBarCard mBackLightDimmerOffsetCard; private SwitchCardView.DSwitchCard mMdssBackLightDimmerEnableCard; private SwitchCardView.DSwitchCard mNegativeToggleCard; private SwitchCardView.DSwitchCard mRegisterHookCard; private SwitchCardView.DSwitchCard mMasterSequenceCard; private SwitchCardView.DSwitchCard mGloveModeCard; @Override public RecyclerView getRecyclerView() { mColorPalette = (ColorPalette) getParentView(R.layout.screen_fragment).findViewById(R.id.colorpalette); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mColorPalette.setVisibility(View.INVISIBLE); return (RecyclerView) getParentView(R.layout.screen_fragment).findViewById(R.id.recycler_view); } @Override public void init(Bundle savedInstanceState) { super.init(savedInstanceState); screenColorInit(); if (Screen.hasKGamma()) kgammaInit(); if (Screen.hasGammaControl()) gammacontrolInit(); if (Screen.hasDsiPanel()) dsipanelInit(); if (mKGammaProfilesCard != null || mGammaControlProfilesCard != null || mDsiPanelProfilesCard != null) additionalProfilesInit(); fb0ColorTempInit(); lcdBackLightInit(); backlightDimmerInit(); mdssBacklightDimmerInit(); if (Screen.hasNegativeToggle()) negativeToggleInit(); mdnieGlobalInit(); if (Screen.hasGloveMode()) gloveModeInit(); } @Override public void postInit(Bundle savedInstanceState) { super.postInit(savedInstanceState); Utils.circleAnimate(mColorPalette, 0, mColorPalette.getHeight()); } private void screenColorInit() { if (Screen.hasColorCalibration()) { List<String> colors = Screen.getColorCalibration(); mColorCalibrationLimits = Screen.getColorCalibrationLimits(); mColorCalibrationCard = new SeekBarCardView.DSeekBarCard[colors.size()]; for (int i = 0; i < mColorCalibrationCard.length; i++) { mColorCalibrationCard[i] = new SeekBarCardView.DSeekBarCard(Screen.getColorCalibrationLimits()); mColorCalibrationCard[i].setTitle(getColor(i)); mColorCalibrationCard[i].setProgress(Screen.getColorCalibrationLimits().indexOf(colors.get(i))); mColorCalibrationCard[i].setOnDSeekBarCardListener(this); addView(mColorCalibrationCard[i]); } } if (Screen.hasColorCalibrationMin() && mColorCalibrationLimits != null) { mColorCalibrationMinCard = new SeekBarCardView.DSeekBarCard(Screen.getColorCalibrationLimits()); mColorCalibrationMinCard.setTitle(getString(R.string.min_rgb)); mColorCalibrationMinCard.setProgress(Screen.getColorCalibrationMin()); mColorCalibrationMinCard.setOnDSeekBarCardListener(this); addView(mColorCalibrationMinCard); } if (Screen.hasInvertScreen()) { mInvertScreenCard = new SwitchCardView.DSwitchCard(); mInvertScreenCard.setDescription(getString(R.string.invert_screen)); mInvertScreenCard.setChecked(Screen.isInvertScreenActive()); mInvertScreenCard.setOnDSwitchCardListener(this); addView(mInvertScreenCard); } if (Screen.hasSaturationIntensity()) { List<String> list = new ArrayList<>(); for (int i = 0; i < 159; i++) list.add(String.valueOf(i)); int saturation = Screen.getSaturationIntensity(); mSaturationIntensityCard = new SeekBarCardView.DSeekBarCard(list); mSaturationIntensityCard.setTitle(getString(R.string.saturation_intensity)); mSaturationIntensityCard.setProgress(saturation == 128 ? 30 : saturation - 225); mSaturationIntensityCard.setEnabled(saturation != 128); mSaturationIntensityCard.setOnDSeekBarCardListener(this); addView(mSaturationIntensityCard); mGrayscaleModeCard = new SwitchCardView.DSwitchCard(); mGrayscaleModeCard.setDescription(getString(R.string.grayscale_mode)); mGrayscaleModeCard.setChecked(saturation == 128); mGrayscaleModeCard.setOnDSwitchCardListener(this); addView(mGrayscaleModeCard); } if (Screen.hasScreenHue()) { List<String> list = new ArrayList<>(); for (int i = 0; i < 1537; i++) list.add(String.valueOf(i)); mScreenHueCard = new SeekBarCardView.DSeekBarCard(list); mScreenHueCard.setTitle(getString(R.string.screen_hue)); mScreenHueCard.setDescription(getString(R.string.screen_hue_summary)); mScreenHueCard.setProgress(Screen.getScreenHue()); mScreenHueCard.setOnDSeekBarCardListener(this); addView(mScreenHueCard); } if (Screen.hasScreenValue()) { List<String> list = new ArrayList<>(); for (int i = 0; i < 256; i++) list.add(String.valueOf(i)); mScreenValueCard = new SeekBarCardView.DSeekBarCard(list); mScreenValueCard.setTitle(getString(R.string.screen_value)); mScreenValueCard.setProgress(Screen.getScreenValue() - 128); mScreenValueCard.setOnDSeekBarCardListener(this); addView(mScreenValueCard); } if (Screen.hasScreenContrast()) { List<String> list = new ArrayList<>(); for (int i = 0; i < 256; i++) list.add(String.valueOf(i)); mScreenContrastCard = new SeekBarCardView.DSeekBarCard(list); mScreenContrastCard.setTitle(getString(R.string.screen_contrast)); mScreenContrastCard.setProgress(Screen.getScreenContrast() - 128); mScreenContrastCard.setOnDSeekBarCardListener(this); addView(mScreenContrastCard); } if (Screen.hasScreenHBM()) { mScreenHBMCard = new SwitchCardView.DSwitchCard(); mScreenHBMCard.setDescription(getString(R.string.high_brightness_mode)); mScreenHBMCard.setChecked(Screen.isScreenHBMActive()); mScreenHBMCard.setOnDSwitchCardListener(this); addView(mScreenHBMCard); } } private void kgammaInit() { DDivider mKGammaDividerCard = new DDivider(); mKGammaDividerCard.setText(getString(R.string.gamma)); addView(mKGammaDividerCard); String blue = Screen.getKGammaBlue(); mKGammaBlueCard = new EditTextCardView.DEditTextCard(); mKGammaBlueCard.setTitle(getString(R.string.blue)); mKGammaBlueCard.setDescription(blue); mKGammaBlueCard.setValue(blue); mKGammaBlueCard.setOnDEditTextCardListener(this); addView(mKGammaBlueCard); String green = Screen.getKGammaGreen(); mKGammaGreenCard = new EditTextCardView.DEditTextCard(); mKGammaGreenCard.setTitle(getString(R.string.green)); mKGammaGreenCard.setDescription(green); mKGammaGreenCard.setValue(green); mKGammaGreenCard.setOnDEditTextCardListener(this); addView(mKGammaGreenCard); String red = Screen.getKGammaRed(); mKGammaRedCard = new EditTextCardView.DEditTextCard(); mKGammaRedCard.setTitle(getString(R.string.red)); mKGammaRedCard.setDescription(red); mKGammaRedCard.setValue(red); mKGammaRedCard.setOnDEditTextCardListener(this); addView(mKGammaRedCard); GammaProfiles.KGammaProfiles kGammaProfiles = Screen.getKGammaProfiles(getActivity()); if (kGammaProfiles != null) { List<String> list = new ArrayList<>(); for (int i = 0; i < kGammaProfiles.length(); i++) list.add(kGammaProfiles.getName(i)); mKGammaProfilesCard = new PopupCardView.DPopupCard(list); mKGammaProfilesCard.setTitle(getString(R.string.gamma_profile)); mKGammaProfilesCard.setDescription(getString(R.string.gamma_profile_summary)); mKGammaProfilesCard.setItem(""); mKGammaProfilesCard.setOnDPopupCardListener(this); addView(mKGammaProfilesCard); } } private void gammacontrolInit() { DDivider mKGammaDividerCard = new DDivider(); mKGammaDividerCard.setText(getString(R.string.gamma)); addView(mKGammaDividerCard); String redGreys = Screen.getRedGreys(); mGammaControlRedGreysCard = new EditTextCardView.DEditTextCard(); mGammaControlRedGreysCard.setTitle(getString(R.string.red_greys)); mGammaControlRedGreysCard.setDescription(redGreys); mGammaControlRedGreysCard.setValue(redGreys); mGammaControlRedGreysCard.setOnDEditTextCardListener(this); addView(mGammaControlRedGreysCard); String redMids = Screen.getRedMids(); mGammaControlRedMidsCard = new EditTextCardView.DEditTextCard(); mGammaControlRedMidsCard.setTitle(getString(R.string.red_mids)); mGammaControlRedMidsCard.setDescription(redMids); mGammaControlRedMidsCard.setValue(redMids); mGammaControlRedMidsCard.setOnDEditTextCardListener(this); addView(mGammaControlRedMidsCard); String redBlacks = Screen.getRedBlacks(); mGammaControlRedBlacksCard = new EditTextCardView.DEditTextCard(); mGammaControlRedBlacksCard.setTitle(getString(R.string.red_blacks)); mGammaControlRedBlacksCard.setDescription(redBlacks); mGammaControlRedBlacksCard.setValue(redBlacks); mGammaControlRedBlacksCard.setOnDEditTextCardListener(this); addView(mGammaControlRedBlacksCard); String redWhites = Screen.getRedWhites(); mGammaControlRedWhitesCard = new EditTextCardView.DEditTextCard(); mGammaControlRedWhitesCard.setTitle(getString(R.string.red_whites)); mGammaControlRedWhitesCard.setDescription(redWhites); mGammaControlRedWhitesCard.setValue(redWhites); mGammaControlRedWhitesCard.setOnDEditTextCardListener(this); addView(mGammaControlRedWhitesCard); String greenGreys = Screen.getGreenGreys(); mGammaControlGreenGreysCard = new EditTextCardView.DEditTextCard(); mGammaControlGreenGreysCard.setTitle(getString(R.string.green_greys)); mGammaControlGreenGreysCard.setDescription(greenGreys); mGammaControlGreenGreysCard.setValue(greenGreys); mGammaControlGreenGreysCard.setOnDEditTextCardListener(this); addView(mGammaControlGreenGreysCard); String greenMids = Screen.getGreenMids(); mGammaControlGreenMidsCard = new EditTextCardView.DEditTextCard(); mGammaControlGreenMidsCard.setTitle(getString(R.string.green_mids)); mGammaControlGreenMidsCard.setDescription(greenMids); mGammaControlGreenMidsCard.setValue(greenMids); mGammaControlGreenMidsCard.setOnDEditTextCardListener(this); addView(mGammaControlGreenMidsCard); String greenBlacks = Screen.getGreenBlacks(); mGammaControlGreenBlacksCard = new EditTextCardView.DEditTextCard(); mGammaControlGreenBlacksCard.setTitle(getString(R.string.green_blacks)); mGammaControlGreenBlacksCard.setDescription(greenBlacks); mGammaControlGreenBlacksCard.setValue(greenBlacks); mGammaControlGreenBlacksCard.setOnDEditTextCardListener(this); addView(mGammaControlGreenBlacksCard); String greenWhites = Screen.getGreenWhites(); mGammaControlGreenWhitesCard = new EditTextCardView.DEditTextCard(); mGammaControlGreenWhitesCard.setTitle(getString(R.string.green_whites)); mGammaControlGreenWhitesCard.setDescription(greenWhites); mGammaControlGreenWhitesCard.setValue(greenWhites); mGammaControlGreenWhitesCard.setOnDEditTextCardListener(this); addView(mGammaControlGreenWhitesCard); String blueGreys = Screen.getBlueGreys(); mGammaControlBlueGreysCard = new EditTextCardView.DEditTextCard(); mGammaControlBlueGreysCard.setTitle(getString(R.string.blue_greys)); mGammaControlBlueGreysCard.setDescription(blueGreys); mGammaControlBlueGreysCard.setValue(blueGreys); mGammaControlBlueGreysCard.setOnDEditTextCardListener(this); addView(mGammaControlBlueGreysCard); String blueMids = Screen.getBlueMids(); mGammaControlBlueMidsCard = new EditTextCardView.DEditTextCard(); mGammaControlBlueMidsCard.setTitle(getString(R.string.blue_mids)); mGammaControlBlueMidsCard.setDescription(blueMids); mGammaControlBlueMidsCard.setValue(blueMids); mGammaControlBlueMidsCard.setOnDEditTextCardListener(this); addView(mGammaControlBlueMidsCard); String blueBlacks = Screen.getBlueBlacks(); mGammaControlBlueBlacksCard = new EditTextCardView.DEditTextCard(); mGammaControlBlueBlacksCard.setTitle(getString(R.string.blue_blacks)); mGammaControlBlueBlacksCard.setDescription(blueBlacks); mGammaControlBlueBlacksCard.setValue(blueBlacks); mGammaControlBlueBlacksCard.setOnDEditTextCardListener(this); addView(mGammaControlBlueBlacksCard); String blueWhites = Screen.getBlueWhites(); mGammaControlBlueWhitesCard = new EditTextCardView.DEditTextCard(); mGammaControlBlueWhitesCard.setTitle(getString(R.string.blue_whites)); mGammaControlBlueWhitesCard.setDescription(blueWhites); mGammaControlBlueWhitesCard.setValue(blueWhites); mGammaControlBlueWhitesCard.setOnDEditTextCardListener(this); addView(mGammaControlBlueWhitesCard); String contrast = Screen.getGammaContrast(); mGammaControlContrastCard = new EditTextCardView.DEditTextCard(); mGammaControlContrastCard.setTitle(getString(R.string.contrast)); mGammaControlContrastCard.setDescription(contrast); mGammaControlContrastCard.setValue(contrast); mGammaControlContrastCard.setOnDEditTextCardListener(this); addView(mGammaControlContrastCard); String brightness = Screen.getGammaBrightness(); mGammaControlBrightnessCard = new EditTextCardView.DEditTextCard(); mGammaControlBrightnessCard.setTitle(getString(R.string.brightness)); mGammaControlBrightnessCard.setDescription(brightness); mGammaControlBrightnessCard.setValue(brightness); mGammaControlBrightnessCard.setOnDEditTextCardListener(this); addView(mGammaControlBrightnessCard); String saturation = Screen.getGammaSaturation(); mGammaControlSaturationCard = new EditTextCardView.DEditTextCard(); mGammaControlSaturationCard.setTitle(getString(R.string.saturation_intensity)); mGammaControlSaturationCard.setDescription(saturation); mGammaControlSaturationCard.setValue(saturation); mGammaControlSaturationCard.setOnDEditTextCardListener(this); addView(mGammaControlSaturationCard); GammaProfiles.GammaControlProfiles gammaControlProfiles = Screen.getGammaControlProfiles(getActivity()); if (gammaControlProfiles != null) { List<String> list = new ArrayList<>(); for (int i = 0; i < gammaControlProfiles.length(); i++) list.add(gammaControlProfiles.getName(i)); mGammaControlProfilesCard = new PopupCardView.DPopupCard(list); mGammaControlProfilesCard.setTitle(getString(R.string.gamma_profile)); mGammaControlProfilesCard.setDescription(getString(R.string.gamma_profile_summary)); mGammaControlProfilesCard.setItem(""); mGammaControlProfilesCard.setOnDPopupCardListener(this); addView(mGammaControlProfilesCard); } } private void dsipanelInit() { DDivider mKGammaDividerCard = new DDivider(); mKGammaDividerCard.setText(getString(R.string.gamma)); addView(mKGammaDividerCard); String blueNegative = Screen.getBlueNegative(); mDsiPanelBlueNegativeCard = new EditTextCardView.DEditTextCard(); mDsiPanelBlueNegativeCard.setTitle(getString(R.string.blue_negative)); mDsiPanelBlueNegativeCard.setDescription(blueNegative); mDsiPanelBlueNegativeCard.setValue(blueNegative); mDsiPanelBlueNegativeCard.setOnDEditTextCardListener(this); addView(mDsiPanelBlueNegativeCard); String bluePositive = Screen.getBluePositive(); mDsiPanelBluePositiveCard = new EditTextCardView.DEditTextCard(); mDsiPanelBluePositiveCard.setTitle(getString(R.string.blue_positive)); mDsiPanelBluePositiveCard.setDescription(bluePositive); mDsiPanelBluePositiveCard.setValue(bluePositive); mDsiPanelBluePositiveCard.setOnDEditTextCardListener(this); addView(mDsiPanelBluePositiveCard); String greenNegative = Screen.getGreenNegative(); mDsiPanelGreenNegativeCard = new EditTextCardView.DEditTextCard(); mDsiPanelGreenNegativeCard.setTitle(getString(R.string.green_negative)); mDsiPanelGreenNegativeCard.setDescription(greenNegative); mDsiPanelGreenNegativeCard.setValue(greenNegative); mDsiPanelGreenNegativeCard.setOnDEditTextCardListener(this); addView(mDsiPanelGreenNegativeCard); String greenPositive = Screen.getGreenPositive(); mDsiPanelGreenPositiveCard = new EditTextCardView.DEditTextCard(); mDsiPanelGreenPositiveCard.setTitle(getString(R.string.green_positive)); mDsiPanelGreenPositiveCard.setDescription(greenPositive); mDsiPanelGreenPositiveCard.setValue(greenPositive); mDsiPanelGreenPositiveCard.setOnDEditTextCardListener(this); addView(mDsiPanelGreenPositiveCard); String redNegative = Screen.getRedNegative(); mDsiPanelRedNegativeCard = new EditTextCardView.DEditTextCard(); mDsiPanelRedNegativeCard.setTitle(getString(R.string.red_negative)); mDsiPanelRedNegativeCard.setDescription(redNegative); mDsiPanelRedNegativeCard.setValue(redNegative); mDsiPanelRedNegativeCard.setOnDEditTextCardListener(this); addView(mDsiPanelRedNegativeCard); String redPositive = Screen.getRedPositive(); mDsiPanelRedPositiveCard = new EditTextCardView.DEditTextCard(); mDsiPanelRedPositiveCard.setTitle(getString(R.string.red_positive)); mDsiPanelRedPositiveCard.setDescription(redPositive); mDsiPanelRedPositiveCard.setValue(redPositive); mDsiPanelRedPositiveCard.setOnDEditTextCardListener(this); addView(mDsiPanelRedPositiveCard); String whitePoint = Screen.getWhitePoint(); mDsiPanelWhitePointCard = new EditTextCardView.DEditTextCard(); mDsiPanelWhitePointCard.setTitle(getString(R.string.white_point)); mDsiPanelWhitePointCard.setDescription(whitePoint); mDsiPanelWhitePointCard.setValue(whitePoint); mDsiPanelWhitePointCard.setOnDEditTextCardListener(this); addView(mDsiPanelWhitePointCard); GammaProfiles.DsiPanelProfiles dsiPanelProfiles = Screen.getDsiPanelProfiles(getActivity()); if (dsiPanelProfiles != null) { List<String> list = new ArrayList<>(); for (int i = 0; i < dsiPanelProfiles.length(); i++) list.add(dsiPanelProfiles.getName(i)); mDsiPanelProfilesCard = new PopupCardView.DPopupCard(list); mDsiPanelProfilesCard.setTitle(getString(R.string.gamma_profile)); mDsiPanelProfilesCard.setDescription(getString(R.string.gamma_profile_summary)); mDsiPanelProfilesCard.setItem(""); mDsiPanelProfilesCard.setOnDPopupCardListener(this); addView(mDsiPanelProfilesCard); } } private void fb0ColorTempInit() { if (Screen.hasFb0ColorTempEnable()) mScreenColorTempEnableCard = new SwitchCardView.DSwitchCard(); mScreenColorTempEnableCard.setTitle(getString(R.string.color_temp)); mScreenColorTempEnableCard.setDescription(getString(R.string.color_temp_summary)); mScreenColorTempEnableCard.setChecked(Screen.isFb0ColorTempActive()); mScreenColorTempEnableCard.setOnDSwitchCardListener(this); addView(mScreenColorTempEnableCard); } private void additionalProfilesInit() { mAdditionalProfilesCard = new CardViewItem.DCardView(); mAdditionalProfilesCard.setTitle(getString(R.string.additional_profiles)); mAdditionalProfilesCard.setDescription(getString(R.string.additional_profiles_summary)); mAdditionalProfilesCard.setOnDCardListener(this); addView(mAdditionalProfilesCard); } private void lcdBackLightInit() { List<DAdapter.DView> views = new ArrayList<>(); if (Screen.hasBrightnessMode()) { mBrightnessModeCard = new SwitchCardView.DSwitchCard(); mBrightnessModeCard.setDescription(getString(R.string.brightness_mode)); mBrightnessModeCard.setChecked(Screen.isBrightnessModeActive()); mBrightnessModeCard.setOnDSwitchCardListener(this); views.add(mBrightnessModeCard); } if (Screen.hasLcdMinBrightness()) { List<String> list = new ArrayList<>(); for (int i = 2; i < 115; i++) list.add(String.valueOf(i)); mLcdMinBrightnessCard = new SeekBarCardView.DSeekBarCard(list); mLcdMinBrightnessCard.setTitle(getString(R.string.min_brightness)); mLcdMinBrightnessCard.setDescription(getString(R.string.min_brightness_summary)); mLcdMinBrightnessCard.setProgress(Screen.getLcdMinBrightness() - 2); mLcdMinBrightnessCard.setOnDSeekBarCardListener(this); views.add(mLcdMinBrightnessCard); } if (Screen.hasLcdMaxBrightness()) { List<String> list = new ArrayList<>(); for (int i = 2; i < 115; i++) list.add(String.valueOf(i)); mLcdMaxBrightnessCard = new SeekBarCardView.DSeekBarCard(list); mLcdMaxBrightnessCard.setTitle(getString(R.string.max_brightness)); mLcdMaxBrightnessCard.setDescription(getString(R.string.max_brightness_summary)); mLcdMaxBrightnessCard.setProgress(Screen.getLcdMaxBrightness() - 2); mLcdMaxBrightnessCard.setOnDSeekBarCardListener(this); views.add(mLcdMaxBrightnessCard); } if (views.size() > 0) { DDivider mLcdBackLightDividerCard = new DDivider(); mLcdBackLightDividerCard.setText(getString(R.string.lcd_backlight)); addView(mLcdBackLightDividerCard); addAllViews(views); } } private void backlightDimmerInit() { List<DAdapter.DView> views = new ArrayList<>(); if (Screen.hasBackLightDimmerEnable()) { mBackLightDimmerEnableCard = new SwitchCardView.DSwitchCard(); mBackLightDimmerEnableCard.setDescription(getString(R.string.backlight_dimmer)); mBackLightDimmerEnableCard.setChecked(Screen.isBackLightDimmerActive()); mBackLightDimmerEnableCard.setOnDSwitchCardListener(this); views.add(mBackLightDimmerEnableCard); } if (Screen.hasMinBrightness()) { List<String> list = new ArrayList<>(); for (int i = 0; i <= Screen.getMaxMinBrightness(); i++) list.add(String.valueOf(i)); mBackLightDimmerMinBrightnessCard = new SeekBarCardView.DSeekBarCard(list); mBackLightDimmerMinBrightnessCard.setTitle(getString(R.string.min_brightness)); mBackLightDimmerMinBrightnessCard.setDescription(getString(R.string.min_brightness_summary)); mBackLightDimmerMinBrightnessCard.setProgress(Screen.getCurMinBrightness()); mBackLightDimmerMinBrightnessCard.setOnDSeekBarCardListener(this); views.add(mBackLightDimmerMinBrightnessCard); } if (Screen.hasBackLightDimmerThreshold()) { List<String> list = new ArrayList<>(); for (int i = 0; i < 51; i++) list.add(String.valueOf(i)); mBackLightDimmerThresholdCard = new SeekBarCardView.DSeekBarCard(list); mBackLightDimmerThresholdCard.setTitle(getString(R.string.threshold)); mBackLightDimmerThresholdCard.setProgress(Screen.getBackLightDimmerThreshold()); mBackLightDimmerThresholdCard.setOnDSeekBarCardListener(this); views.add(mBackLightDimmerThresholdCard); } if (Screen.hasBackLightDimmerOffset()) { List<String> list = new ArrayList<>(); for (int i = 0; i < 51; i++) list.add(String.valueOf(i)); mBackLightDimmerOffsetCard = new SeekBarCardView.DSeekBarCard(list); mBackLightDimmerOffsetCard.setTitle(getString(R.string.offset)); mBackLightDimmerOffsetCard.setProgress(Screen.getBackLightDimmerOffset()); mBackLightDimmerOffsetCard.setOnDSeekBarCardListener(this); views.add(mBackLightDimmerOffsetCard); } if (views.size() > 0) { DDivider mBackLightDimmerDividerCard = new DDivider(); mBackLightDimmerDividerCard.setText(getString(R.string.backlight_dimmer)); addView(mBackLightDimmerDividerCard); addAllViews(views); } } private void mdssBacklightDimmerInit() { if (Screen.hasMdssBackLightDimmerEnable()) { mMdssBackLightDimmerEnableCard = new SwitchCardView.DSwitchCard(); mMdssBackLightDimmerEnableCard.setTitle(getString(R.string.backlight_dimmer)); mMdssBackLightDimmerEnableCard.setDescription(getString(R.string.brightness_mode)); mMdssBackLightDimmerEnableCard.setChecked(Screen.isMdssBackLightDimmerActive()); mMdssBackLightDimmerEnableCard.setOnDSwitchCardListener(this); addView(mMdssBackLightDimmerEnableCard); } } private void negativeToggleInit() { mNegativeToggleCard = new SwitchCardView.DSwitchCard(); mNegativeToggleCard.setTitle(getString(R.string.negative_toggle)); mNegativeToggleCard.setDescription(getString(R.string.negative_toggle_summary)); mNegativeToggleCard.setChecked(Screen.isNegativeToggleActive()); mNegativeToggleCard.setOnDSwitchCardListener(this); addView(mNegativeToggleCard); } private void mdnieGlobalInit() { List<DAdapter.DView> views = new ArrayList<>(); if (Screen.hasRegisterHook()) { mRegisterHookCard = new SwitchCardView.DSwitchCard(); mRegisterHookCard.setTitle(getString(R.string.register_hook)); mRegisterHookCard.setDescription(getString(R.string.register_hook_summary)); mRegisterHookCard.setChecked(Screen.isRegisterHookActive()); mRegisterHookCard.setOnDSwitchCardListener(this); views.add(mRegisterHookCard); } if (Screen.hasMasterSequence()) { mMasterSequenceCard = new SwitchCardView.DSwitchCard(); mMasterSequenceCard.setTitle(getString(R.string.master_sequence)); mMasterSequenceCard.setDescription(getString(R.string.master_sequence_summary)); mMasterSequenceCard.setChecked(Screen.isMasterSequenceActive()); mMasterSequenceCard.setOnDSwitchCardListener(this); views.add(mMasterSequenceCard); } if (views.size() > 0) { DDivider mMdnieGlobalDivider = new DDivider(); mMdnieGlobalDivider.setText(getString(R.string.mdnie_global_controls)); addView(mMdnieGlobalDivider); addAllViews(views); } } private void gloveModeInit() { mGloveModeCard = new SwitchCardView.DSwitchCard(); mGloveModeCard.setTitle(getString(R.string.glove_mode)); mGloveModeCard.setDescription(getString(R.string.glove_mode_summary)); mGloveModeCard.setChecked(Screen.isGloveModeActive()); mGloveModeCard.setOnDSwitchCardListener(this); addView(mGloveModeCard); } @Override public void onChanged(SeekBarCardView.DSeekBarCard dSeekBarCard, int position) { if (dSeekBarCard == mColorCalibrationMinCard) { for (SeekBarCardView.DSeekBarCard seekBarCardView : mColorCalibrationCard) if (position > seekBarCardView.getProgress()) seekBarCardView.setProgress(position); } else { if (mColorCalibrationCard != null) for (SeekBarCardView.DSeekBarCard seekBarCardView : mColorCalibrationCard) if (dSeekBarCard == seekBarCardView) { if (mColorCalibrationMinCard != null) if (position < mColorCalibrationMinCard.getProgress()) mColorCalibrationMinCard.setProgress(position); return; } } } @Override public void onStop(SeekBarCardView.DSeekBarCard dSeekBarCard, int position) { if (dSeekBarCard == mColorCalibrationMinCard) Screen.setColorCalibrationMin(Utils.stringToInt(mColorCalibrationLimits.get(position)), getActivity()); else if (dSeekBarCard == mSaturationIntensityCard) Screen.setSaturationIntensity(position + 225, getActivity()); else if (dSeekBarCard == mScreenHueCard) Screen.setScreenHue(position, getActivity()); else if (dSeekBarCard == mScreenValueCard) Screen.setScreenValue(position + 128, getActivity()); else if (dSeekBarCard == mScreenContrastCard) Screen.setScreenContrast(position + 128, getActivity()); else if (dSeekBarCard == mLcdMinBrightnessCard) Screen.setLcdMinBrightness(position + 2, getActivity()); else if (dSeekBarCard == mLcdMaxBrightnessCard) Screen.setLcdMaxBrightness(position + 2, getActivity()); else if (dSeekBarCard == mBackLightDimmerMinBrightnessCard) Screen.setMinBrightness(position, getActivity()); else if (dSeekBarCard == mBackLightDimmerThresholdCard) Screen.setBackLightDimmerThreshold(position, getActivity()); else if (dSeekBarCard == mBackLightDimmerOffsetCard) Screen.setBackLightDimmerOffset(position, getActivity()); else { for (SeekBarCardView.DSeekBarCard seekBarCardView : mColorCalibrationCard) if (dSeekBarCard == seekBarCardView) { if (mColorCalibrationMinCard != null) { int current = Utils.stringToInt(mColorCalibrationLimits.get(position)); if (Screen.getColorCalibrationMin() > current) Screen.setColorCalibrationMin(current, getActivity()); } try { int r = mColorCalibrationCard[0].getProgress(); int g = mColorCalibrationCard[1].getProgress(); int b = mColorCalibrationCard[2].getProgress(); Screen.setColorCalibration(mColorCalibrationLimits.get(r) + " " + mColorCalibrationLimits.get(g) + " " + mColorCalibrationLimits.get(b), getActivity()); } catch (ArrayIndexOutOfBoundsException e) { Utils.errorDialog(getActivity(), e); e.printStackTrace(); } return; } } } @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { if (dSwitchCard == mInvertScreenCard) Screen.activateInvertScreen(checked, getActivity()); else if (dSwitchCard == mGrayscaleModeCard) { mSaturationIntensityCard.setEnabled(!checked); Screen.activateGrayscaleMode(checked, getActivity()); if (!checked) mSaturationIntensityCard.setProgress(30); } else if (dSwitchCard == mScreenHBMCard) Screen.activateScreenHBM(checked, getActivity()); else if (dSwitchCard == mScreenColorTempEnableCard) Screen.activateFb0ColorTemp(checked, getActivity()); else if (dSwitchCard == mBackLightDimmerEnableCard) Screen.activateBackLightDimmer(checked, getActivity()); else if (dSwitchCard == mMdssBackLightDimmerEnableCard) Screen.activateMdssBackLightDimmer(checked, getActivity()); else if (dSwitchCard == mBrightnessModeCard) Screen.activateBrightnessMode(checked, getActivity()); else if (dSwitchCard == mNegativeToggleCard) Screen.activateNegativeToggle(checked, getActivity()); else if (dSwitchCard == mRegisterHookCard) Screen.activateRegisterHook(checked, getActivity()); else if (dSwitchCard == mMasterSequenceCard) Screen.activateMasterSequence(checked, getActivity()); else if (dSwitchCard == mGloveModeCard) Screen.activateGloveMode(checked, getActivity()); } @Override public void onApply(EditTextCardView.DEditTextCard dEditTextCard, String value) { dEditTextCard.setDescription(value); if (dEditTextCard == mKGammaRedCard) Screen.setKGammaRed(value, getActivity()); else if (dEditTextCard == mKGammaGreenCard) Screen.setKGammaGreen(value, getActivity()); else if (dEditTextCard == mKGammaBlueCard) Screen.setKGammaBlue(value, getActivity()); else if (dEditTextCard == mGammaControlRedGreysCard) Screen.setRedGreys(value, getActivity()); else if (dEditTextCard == mGammaControlRedMidsCard) Screen.setRedMids(value, getActivity()); else if (dEditTextCard == mGammaControlRedBlacksCard) Screen.setRedBlacks(value, getActivity()); else if (dEditTextCard == mGammaControlRedWhitesCard) Screen.setRedWhites(value, getActivity()); else if (dEditTextCard == mGammaControlGreenGreysCard) Screen.setGreenGreys(value, getActivity()); else if (dEditTextCard == mGammaControlGreenMidsCard) Screen.setGreenMids(value, getActivity()); else if (dEditTextCard == mGammaControlGreenBlacksCard) Screen.setGreenBlacks(value, getActivity()); else if (dEditTextCard == mGammaControlGreenWhitesCard) Screen.setGreenWhites(value, getActivity()); else if (dEditTextCard == mGammaControlBlueGreysCard) Screen.setBlueGreys(value, getActivity()); else if (dEditTextCard == mGammaControlBlueMidsCard) Screen.setBlueMids(value, getActivity()); else if (dEditTextCard == mGammaControlBlueBlacksCard) Screen.setBlueBlacks(value, getActivity()); else if (dEditTextCard == mGammaControlBlueWhitesCard) Screen.setBlueWhites(value, getActivity()); else if (dEditTextCard == mGammaControlContrastCard) Screen.setGammaContrast(value, getActivity()); else if (dEditTextCard == mGammaControlBrightnessCard) Screen.setGammaBrightness(value, getActivity()); else if (dEditTextCard == mGammaControlSaturationCard) Screen.setGammaSaturation(value, getActivity()); else if (dEditTextCard == mDsiPanelRedPositiveCard) Screen.setRedPositive(value, getActivity()); else if (dEditTextCard == mDsiPanelRedNegativeCard) Screen.setRedNegative(value, getActivity()); else if (dEditTextCard == mDsiPanelGreenPositiveCard) Screen.setGreenPositive(value, getActivity()); else if (dEditTextCard == mDsiPanelGreenNegativeCard) Screen.setGreenNegative(value, getActivity()); else if (dEditTextCard == mDsiPanelBluePositiveCard) Screen.setBluePositive(value, getActivity()); else if (dEditTextCard == mDsiPanelBlueNegativeCard) Screen.setBlueNegative(value, getActivity()); else if (dEditTextCard == mDsiPanelWhitePointCard) Screen.setWhitePoint(value, getActivity()); } @Override public void onItemSelected(PopupCardView.DPopupCard dPopupCard, int position) { if (dPopupCard == mKGammaProfilesCard) { Screen.setKGammaProfile(position, Screen.getKGammaProfiles(getActivity()), getActivity()); refreshKGamma(); } else if (dPopupCard == mGammaControlProfilesCard) { Screen.setGammaControlProfile(position, Screen.getGammaControlProfiles(getActivity()), getActivity()); refreshGammaControl(); } else if (dPopupCard == mDsiPanelProfilesCard) { Screen.setDsiPanelProfile(position, Screen.getDsiPanelProfiles(getActivity()), getActivity()); refreshDsiPanel(); } } @Override public void onClick(CardViewItem.DCardView dCardView) { if (dCardView == mAdditionalProfilesCard) { final ProgressDialog progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage(getString(R.string.loading)); progressDialog.setCancelable(false); progressDialog.show(); new WebpageReader(new WebpageReader.WebpageCallback() { @Override public void onCallback(String raw, String html) { progressDialog.dismiss(); if (getActivity() == null) return; GammaProfiles gammaProfiles = new GammaProfiles(raw); String path = getActivity().getApplicationContext().getCacheDir() + "/gamma_profiles.json"; if (gammaProfiles.readable()) { Tools.writeFile(path, raw, false, false); showMoreGammaProfiles(gammaProfiles); } else { if (Utils.existFile(path)) { gammaProfiles.refresh(Utils.readFile(path)); if (gammaProfiles.readable()) { showMoreGammaProfiles(gammaProfiles); return; } } Utils.toast(getString(R.string.no_internet), getActivity()); } } }).execute(Constants.GAMMA_URL); } } private String getColor(int position) { switch (position) { case 0: return getString(R.string.red); case 1: return getString(R.string.green); case 2: return getString(R.string.blue); default: return null; } } private void showMoreGammaProfiles(GammaProfiles gammaProfiles) { GammaProfiles.GammaProfile profile = null; int screen = -1; if (mKGammaProfilesCard != null) { profile = gammaProfiles.getKGamma(); screen = 0; } else if (mGammaControlProfilesCard != null) { profile = gammaProfiles.getGammaControl(); screen = 1; } else if (mDsiPanelProfilesCard != null) { profile = gammaProfiles.getDsiPanelProfiles(); screen = 2; } if (profile == null) Utils.toast(getString(R.string.no_additional_profiles), getActivity()); else { String[] names = new String[profile.length()]; for (int i = 0; i < names.length; i++) names[i] = profile.getName(i); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final int profileType = screen; final GammaProfiles.GammaProfile gammaProfile = profile; builder.setItems(names, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (profileType) { case 0: Screen.setKGammaProfile(which, (GammaProfiles.KGammaProfiles) gammaProfile, getActivity()); refreshKGamma(); break; case 1: Screen.setGammaControlProfile(which, (GammaProfiles.GammaControlProfiles) gammaProfile, getActivity()); refreshGammaControl(); break; case 2: Screen.setDsiPanelProfile(which, (GammaProfiles.DsiPanelProfiles) gammaProfile, getActivity()); refreshDsiPanel(); break; } } }).show(); } } private void refreshKGamma() { for (int i = 0; i < mColorCalibrationCard.length; i++) mColorCalibrationCard[i].setProgress(Screen.getColorCalibrationLimits() .indexOf(Screen.getColorCalibration().get(i))); String red = Screen.getKGammaRed(); mKGammaRedCard.setDescription(red); mKGammaRedCard.setValue(red); String green = Screen.getKGammaGreen(); mKGammaGreenCard.setDescription(green); mKGammaGreenCard.setValue(green); String blue = Screen.getKGammaBlue(); mKGammaBlueCard.setDescription(blue); mKGammaBlueCard.setValue(blue); } private void refreshGammaControl() { if (mColorCalibrationCard != null) for (int i = 0; i < mColorCalibrationCard.length; i++) if (mColorCalibrationCard[i] != null) mColorCalibrationCard[i].setProgress(Screen.getColorCalibrationLimits() .indexOf(Screen.getColorCalibration().get(i))); String redGreys = Screen.getRedGreys(); mGammaControlRedGreysCard.setDescription(redGreys); mGammaControlRedGreysCard.setValue(redGreys); String redMids = Screen.getRedMids(); mGammaControlRedMidsCard.setDescription(redMids); mGammaControlRedMidsCard.setValue(redMids); String redBlacks = Screen.getRedBlacks(); mGammaControlRedBlacksCard.setDescription(redBlacks); mGammaControlRedBlacksCard.setValue(redBlacks); String redWhites = Screen.getRedWhites(); mGammaControlRedWhitesCard.setDescription(redWhites); mGammaControlRedWhitesCard.setValue(redWhites); String greenGreys = Screen.getGreenGreys(); mGammaControlGreenGreysCard.setDescription(greenGreys); mGammaControlGreenGreysCard.setValue(greenGreys); String greenMids = Screen.getGreenMids(); mGammaControlGreenMidsCard.setDescription(greenMids); mGammaControlGreenMidsCard.setValue(greenMids); String greenBlacks = Screen.getGreenBlacks(); mGammaControlGreenBlacksCard.setDescription(greenBlacks); mGammaControlGreenBlacksCard.setValue(greenBlacks); String greenWhites = Screen.getGreenWhites(); mGammaControlGreenWhitesCard.setDescription(greenWhites); mGammaControlGreenWhitesCard.setValue(greenWhites); String blueGreys = Screen.getBlueGreys(); mGammaControlBlueGreysCard.setDescription(blueGreys); mGammaControlBlueGreysCard.setValue(blueGreys); String blueMids = Screen.getBlueMids(); mGammaControlBlueMidsCard.setDescription(blueMids); mGammaControlBlueMidsCard.setValue(blueMids); String blueBlacks = Screen.getBlueBlacks(); mGammaControlBlueBlacksCard.setDescription(blueBlacks); mGammaControlBlueBlacksCard.setValue(blueBlacks); String blueWhites = Screen.getBlueWhites(); mGammaControlBlueWhitesCard.setDescription(blueWhites); mGammaControlBlueWhitesCard.setValue(blueWhites); String contrast = Screen.getGammaContrast(); mGammaControlContrastCard.setDescription(contrast); mGammaControlContrastCard.setValue(contrast); String brightness = Screen.getGammaBrightness(); mGammaControlBrightnessCard.setDescription(brightness); mGammaControlBrightnessCard.setValue(brightness); String saturation = Screen.getGammaSaturation(); mGammaControlSaturationCard.setDescription(saturation); mGammaControlSaturationCard.setValue(saturation); } private void refreshDsiPanel() { String blueNegative = Screen.getBlueNegative(); mDsiPanelBlueNegativeCard.setDescription(blueNegative); mDsiPanelBlueNegativeCard.setValue(blueNegative); String bluePositive = Screen.getBluePositive(); mDsiPanelBluePositiveCard.setDescription(bluePositive); mDsiPanelBluePositiveCard.setValue(bluePositive); String greenNegative = Screen.getGreenNegative(); mDsiPanelGreenNegativeCard.setDescription(greenNegative); mDsiPanelGreenNegativeCard.setValue(greenNegative); String greenPositive = Screen.getGreenPositive(); mDsiPanelGreenPositiveCard.setDescription(greenPositive); mDsiPanelGreenPositiveCard.setValue(greenPositive); String redNegative = Screen.getRedNegative(); mDsiPanelRedNegativeCard.setDescription(redNegative); mDsiPanelRedNegativeCard.setValue(redNegative); String redPositive = Screen.getRedPositive(); mDsiPanelRedPositiveCard.setDescription(redPositive); mDsiPanelRedPositiveCard.setValue(redPositive); String whitePoint = Screen.getWhitePoint(); mDsiPanelWhitePointCard.setDescription(whitePoint); mDsiPanelWhitePointCard.setValue(whitePoint); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.management.impl; import javax.management.MBeanOperationInfo; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.management.AddressControl; import org.apache.activemq.artemis.core.paging.PagingManager; import org.apache.activemq.artemis.core.paging.PagingStore; import org.apache.activemq.artemis.core.persistence.StorageManager; import org.apache.activemq.artemis.core.postoffice.Binding; import org.apache.activemq.artemis.core.postoffice.Bindings; import org.apache.activemq.artemis.core.postoffice.PostOffice; import org.apache.activemq.artemis.core.postoffice.QueueBinding; import org.apache.activemq.artemis.core.security.CheckType; import org.apache.activemq.artemis.core.security.Role; import org.apache.activemq.artemis.core.settings.HierarchicalRepository; import org.apache.activemq.artemis.utils.json.JSONArray; import org.apache.activemq.artemis.utils.json.JSONObject; public class AddressControlImpl extends AbstractControl implements AddressControl { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- private final SimpleString address; private final PostOffice postOffice; private final PagingManager pagingManager; private final HierarchicalRepository<Set<Role>> securityRepository; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public AddressControlImpl(final SimpleString address, final PostOffice postOffice, final PagingManager pagingManager, final StorageManager storageManager, final HierarchicalRepository<Set<Role>> securityRepository) throws Exception { super(AddressControl.class, storageManager); this.address = address; this.postOffice = postOffice; this.pagingManager = pagingManager; this.securityRepository = securityRepository; } // Public -------------------------------------------------------- // AddressControlMBean implementation ---------------------------- public String getAddress() { return address.toString(); } public String[] getQueueNames() throws Exception { clearIO(); try { Bindings bindings = postOffice.getBindingsForAddress(address); List<String> queueNames = new ArrayList<String>(); for (Binding binding : bindings.getBindings()) { if (binding instanceof QueueBinding) { queueNames.add(binding.getUniqueName().toString()); } } return queueNames.toArray(new String[queueNames.size()]); } catch (Throwable t) { throw new IllegalStateException(t.getMessage()); } finally { blockOnIO(); } } public String[] getBindingNames() throws Exception { clearIO(); try { Bindings bindings = postOffice.getBindingsForAddress(address); String[] bindingNames = new String[bindings.getBindings().size()]; int i = 0; for (Binding binding : bindings.getBindings()) { bindingNames[i++] = binding.getUniqueName().toString(); } return bindingNames; } catch (Throwable t) { throw new IllegalStateException(t.getMessage()); } finally { blockOnIO(); } } public Object[] getRoles() throws Exception { clearIO(); try { Set<Role> roles = securityRepository.getMatch(address.toString()); Object[] objRoles = new Object[roles.size()]; int i = 0; for (Role role : roles) { objRoles[i++] = new Object[]{role.getName(), CheckType.SEND.hasRole(role), CheckType.CONSUME.hasRole(role), CheckType.CREATE_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_DURABLE_QUEUE.hasRole(role), CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), CheckType.MANAGE.hasRole(role)}; } return objRoles; } finally { blockOnIO(); } } public String getRolesAsJSON() throws Exception { clearIO(); try { JSONArray json = new JSONArray(); Set<Role> roles = securityRepository.getMatch(address.toString()); for (Role role : roles) { json.put(new JSONObject(role)); } return json.toString(); } finally { blockOnIO(); } } public long getNumberOfBytesPerPage() throws Exception { clearIO(); try { return pagingManager.getPageStore(address).getPageSizeBytes(); } finally { blockOnIO(); } } public long getAddressSize() throws Exception { clearIO(); try { return pagingManager.getPageStore(address).getAddressSize(); } finally { blockOnIO(); } } public long getNumberOfMessages() throws Exception { clearIO(); long totalMsgs = 0; try { Bindings bindings = postOffice.getBindingsForAddress(address); List<String> queueNames = new ArrayList<String>(); for (Binding binding : bindings.getBindings()) { if (binding instanceof QueueBinding) { totalMsgs += ((QueueBinding) binding).getQueue().getMessageCount(); } } return totalMsgs; } catch (Throwable t) { throw new IllegalStateException(t.getMessage()); } finally { blockOnIO(); } } public boolean isPaging() throws Exception { clearIO(); try { return pagingManager.getPageStore(address).isPaging(); } finally { blockOnIO(); } } public int getNumberOfPages() throws Exception { clearIO(); try { PagingStore pageStore = pagingManager.getPageStore(address); if (!pageStore.isPaging()) { return 0; } else { return pagingManager.getPageStore(address).getNumberOfPages(); } } finally { blockOnIO(); } } @Override protected MBeanOperationInfo[] fillMBeanOperationInfo() { return MBeanInfoHelper.getMBeanOperationsInfo(AddressControl.class); } // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.toolbar.menu_button; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import androidx.annotation.DrawableRes; import androidx.annotation.VisibleForTesting; import androidx.core.view.ViewCompat; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.supplier.Supplier; import org.chromium.chrome.browser.theme.ThemeColorProvider.TintObserver; import org.chromium.chrome.browser.theme.ThemeUtils; import org.chromium.chrome.browser.toolbar.R; import org.chromium.chrome.browser.ui.appmenu.AppMenuButtonHelper; import org.chromium.components.browser_ui.widget.animation.Interpolators; import org.chromium.components.browser_ui.widget.highlight.PulseDrawable; import org.chromium.ui.interpolators.BakedBezierInterpolator; /** * The overflow menu button. */ public class MenuButton extends FrameLayout implements TintObserver { /** The {@link ImageButton} for the menu button. */ private ImageButton mMenuImageButton; /** The view for the update badge. */ private ImageView mUpdateBadgeView; private boolean mUseLightDrawables; private AppMenuButtonHelper mAppMenuButtonHelper; private boolean mHighlightingMenu; private PulseDrawable mHighlightDrawable; private Drawable mOriginalBackground; private AnimatorSet mMenuBadgeAnimatorSet; private boolean mIsMenuBadgeAnimationRunning; /** A provider that notifies components when the theme color changes.*/ private BitmapDrawable mMenuImageButtonAnimationDrawable; private BitmapDrawable mUpdateBadgeAnimationDrawable; private Supplier<MenuButtonState> mStateSupplier; public MenuButton(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); mMenuImageButton = findViewById(R.id.menu_button); mUpdateBadgeView = findViewById(R.id.menu_badge); mOriginalBackground = getBackground(); } public void setAppMenuButtonHelper(AppMenuButtonHelper appMenuButtonHelper) { mAppMenuButtonHelper = appMenuButtonHelper; mMenuImageButton.setOnTouchListener(mAppMenuButtonHelper); mMenuImageButton.setAccessibilityDelegate(mAppMenuButtonHelper.getAccessibilityDelegate()); } public ImageButton getImageButton() { return mMenuImageButton; } @Override public void setOnKeyListener(OnKeyListener onKeyListener) { if (mMenuImageButton == null) return; mMenuImageButton.setOnKeyListener(onKeyListener); } /** * Sets the update badge to visible. * * @param visible Whether the update badge should be visible. Always sets visibility to GONE * if the update type does not require a badge. * TODO(crbug.com/865801): Clean this up when MenuButton and UpdateMenuItemHelper is MVCed. */ private void setUpdateBadgeVisibility(boolean visible) { if (mUpdateBadgeView == null) return; mUpdateBadgeView.setVisibility(visible ? View.VISIBLE : View.GONE); if (visible) updateImageResources(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { updateImageResources(); } } private void updateImageResources() { mMenuImageButtonAnimationDrawable = (BitmapDrawable) mMenuImageButton.getDrawable() .getConstantState() .newDrawable() .mutate(); mMenuImageButtonAnimationDrawable.setBounds(mMenuImageButton.getPaddingLeft(), mMenuImageButton.getPaddingTop(), mMenuImageButton.getWidth() - mMenuImageButton.getPaddingRight(), mMenuImageButton.getHeight() - mMenuImageButton.getPaddingBottom()); mMenuImageButtonAnimationDrawable.setGravity(Gravity.CENTER); int color = ThemeUtils.getThemedToolbarIconTint(getContext(), mUseLightDrawables) .getDefaultColor(); mMenuImageButtonAnimationDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN); // As an optimization, don't re-calculate drawable state for the update badge unless we // intend to actually show it. // Note(david@vivaldi.com): When the button is placed in the tab switcher |mStateSupplier| // is always null. MenuButtonState buttonState = null; if (mStateSupplier != null) buttonState = mStateSupplier.get(); if (buttonState == null || mUpdateBadgeView == null) return; @DrawableRes int drawable = mUseLightDrawables ? buttonState.lightBadgeIcon : buttonState.darkBadgeIcon; mUpdateBadgeView.setImageDrawable( ApiCompatibilityUtils.getDrawable(getResources(), drawable)); mUpdateBadgeAnimationDrawable = (BitmapDrawable) mUpdateBadgeView.getDrawable() .getConstantState() .newDrawable() .mutate(); mUpdateBadgeAnimationDrawable.setBounds(mUpdateBadgeView.getPaddingLeft(), mUpdateBadgeView.getPaddingTop(), mUpdateBadgeView.getWidth() - mUpdateBadgeView.getPaddingRight(), mUpdateBadgeView.getHeight() - mUpdateBadgeView.getPaddingBottom()); mUpdateBadgeAnimationDrawable.setGravity(Gravity.CENTER); } /** * Set the supplier of menu button state. * @param supplier Supplier of menu button state. */ void setStateSupplier(Supplier<MenuButtonState> supplier) { mStateSupplier = supplier; } /** * Show the update badge on the app menu button. * @param animate Whether to animate the showing of the update badge. */ void showAppMenuUpdateBadge(boolean animate) { if (mUpdateBadgeView == null || mMenuImageButton == null) { return; } updateImageResources(); if (!animate || mIsMenuBadgeAnimationRunning) { setUpdateBadgeVisibility(true); return; } // Set initial states. mUpdateBadgeView.setAlpha(0.f); mUpdateBadgeView.setVisibility(View.VISIBLE); mMenuBadgeAnimatorSet = createShowUpdateBadgeAnimation(mMenuImageButton, mUpdateBadgeView); mMenuBadgeAnimatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { mIsMenuBadgeAnimationRunning = true; } @Override public void onAnimationEnd(Animator animation) { mIsMenuBadgeAnimationRunning = false; } @Override public void onAnimationCancel(Animator animation) { mIsMenuBadgeAnimationRunning = false; } }); mMenuBadgeAnimatorSet.start(); } /** * Remove the update badge on the app menu button. * @param animate Whether to animate the hiding of the update badge. */ void removeAppMenuUpdateBadge(boolean animate) { if (mUpdateBadgeView == null || !isShowingAppMenuUpdateBadge()) return; if (!animate) { setUpdateBadgeVisibility(false); return; } if (mIsMenuBadgeAnimationRunning && mMenuBadgeAnimatorSet != null) { mMenuBadgeAnimatorSet.cancel(); } // Set initial states. mMenuImageButton.setAlpha(0.f); mMenuBadgeAnimatorSet = createHideUpdateBadgeAnimation(mMenuImageButton, mUpdateBadgeView); mMenuBadgeAnimatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { mIsMenuBadgeAnimationRunning = true; } @Override public void onAnimationEnd(Animator animation) { mIsMenuBadgeAnimationRunning = false; } @Override public void onAnimationCancel(Animator animation) { mIsMenuBadgeAnimationRunning = false; } }); mMenuBadgeAnimatorSet.start(); } /** * @return Whether the update badge is showing. */ boolean isShowingAppMenuUpdateBadge() { return mUpdateBadgeView != null && mUpdateBadgeView.getVisibility() == View.VISIBLE; } void updateContentDescription(String description) { mMenuImageButton.setContentDescription(description); } /** * Sets the menu button's background depending on whether or not we are highlighting and whether * or not we are using light or dark assets. */ private void updateMenuButtonHighlightDrawable() { // Return if onFinishInflate didn't finish if (mMenuImageButton == null) return; if (mHighlightingMenu) { if (mHighlightDrawable == null) { mHighlightDrawable = PulseDrawable.createCircle(getContext()); mHighlightDrawable.setInset(ViewCompat.getPaddingStart(mMenuImageButton), mMenuImageButton.getPaddingTop(), ViewCompat.getPaddingEnd(mMenuImageButton), mMenuImageButton.getPaddingBottom()); } mHighlightDrawable.setUseLightPulseColor(getContext(), mUseLightDrawables); setBackground(mHighlightDrawable); mHighlightDrawable.start(); } else { setBackground(mOriginalBackground); } } void setMenuButtonHighlight(boolean highlight) { mHighlightingMenu = highlight; updateMenuButtonHighlightDrawable(); } /** * Draws the current visual state of this component for the purposes of rendering the tab * switcher animation, setting the alpha to fade the view by the appropriate amount. * @param canvas Canvas to draw to. * @param alpha Integer (0-255) alpha level to draw at. */ public void drawTabSwitcherAnimationOverlay(Canvas canvas, int alpha) { Drawable drawable = getTabSwitcherAnimationDrawable(); drawable.setAlpha(alpha); drawable.draw(canvas); } @VisibleForTesting public boolean getUseLightDrawablesForTesting() { return mUseLightDrawables; } @Override public void onTintChanged(ColorStateList tintList, boolean useLight) { ApiCompatibilityUtils.setImageTintList(mMenuImageButton, tintList); mUseLightDrawables = useLight; updateImageResources(); updateMenuButtonHighlightDrawable(); } @VisibleForTesting Drawable getTabSwitcherAnimationDrawable() { if (mUpdateBadgeAnimationDrawable == null && mMenuImageButtonAnimationDrawable == null) { updateImageResources(); } return isShowingAppMenuUpdateBadge() ? mUpdateBadgeAnimationDrawable : mMenuImageButtonAnimationDrawable; } /** * Creates an {@link AnimatorSet} for showing the update badge that is displayed on top * of the app menu button. * * @param menuButton The {@link View} containing the app menu button. * @param menuBadge The {@link View} containing the update badge. * @return An {@link AnimatorSet} to run when showing the update badge. */ private static AnimatorSet createShowUpdateBadgeAnimation( final View menuButton, final View menuBadge) { // Create badge ObjectAnimators. ObjectAnimator badgeFadeAnimator = ObjectAnimator.ofFloat(menuBadge, View.ALPHA, 1.f); badgeFadeAnimator.setInterpolator(BakedBezierInterpolator.FADE_IN_CURVE); int pixelTranslation = menuBadge.getResources().getDimensionPixelSize(R.dimen.menu_badge_translation_y); ObjectAnimator badgeTranslateYAnimator = ObjectAnimator.ofFloat(menuBadge, View.TRANSLATION_Y, pixelTranslation, 0.f); badgeTranslateYAnimator.setInterpolator(BakedBezierInterpolator.TRANSFORM_CURVE); // Create menu button ObjectAnimator. ObjectAnimator menuButtonFadeAnimator = ObjectAnimator.ofFloat(menuButton, View.ALPHA, 0.f); menuButtonFadeAnimator.setInterpolator(Interpolators.LINEAR_INTERPOLATOR); // Create AnimatorSet and listeners. AnimatorSet set = new AnimatorSet(); set.playTogether(badgeFadeAnimator, badgeTranslateYAnimator, menuButtonFadeAnimator); set.setDuration(350); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // Make sure the menu button is visible again. menuButton.setAlpha(1.f); } @Override public void onAnimationCancel(Animator animation) { // Jump to the end state if the animation is canceled. menuBadge.setAlpha(1.f); menuBadge.setTranslationY(0.f); menuButton.setAlpha(1.f); } }); return set; } /** * Creates an {@link AnimatorSet} for hiding the update badge that is displayed on top * of the app menu button. * * @param menuButton The {@link View} containing the app menu button. * @param menuBadge The {@link View} containing the update badge. * @return An {@link AnimatorSet} to run when hiding the update badge. */ private static AnimatorSet createHideUpdateBadgeAnimation( final View menuButton, final View menuBadge) { // Create badge ObjectAnimator. ObjectAnimator badgeFadeAnimator = ObjectAnimator.ofFloat(menuBadge, View.ALPHA, 0.f); badgeFadeAnimator.setInterpolator(BakedBezierInterpolator.FADE_OUT_CURVE); // Create menu button ObjectAnimator. ObjectAnimator menuButtonFadeAnimator = ObjectAnimator.ofFloat(menuButton, View.ALPHA, 1.f); menuButtonFadeAnimator.setInterpolator(BakedBezierInterpolator.FADE_IN_CURVE); // Create AnimatorSet and listeners. AnimatorSet set = new AnimatorSet(); set.playTogether(badgeFadeAnimator, menuButtonFadeAnimator); set.setDuration(200); set.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { menuBadge.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { // Jump to the end state if the animation is canceled. menuButton.setAlpha(1.f); menuBadge.setVisibility(View.GONE); } }); return set; } @VisibleForTesting void setOriginalBackgroundForTesting(Drawable background) { mOriginalBackground = background; setBackground(mOriginalBackground); } }