language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
Java | class Score implements Comparable {
double s;
int i;
int j;
public Score(double s, int i, int j) {
this.s = s;
this.i = i;
this.j = j;
}
public int getIndex1() {
return i;
}
public int getIndex2() {
return j;
}
public int compareTo(Object o) {
Score other = (Score) o;
if (this.s < other.s) {
return -1;
} else if (this.s > other.s) {
return 1;
} else {
int cmp = this.i - other.i;
if (cmp == 0) {
cmp = this.j - other.j;
}
return cmp;
}
}
} |
Java | public class RtMovieDTO {
private String title;
private String imageURL;
private byte score;
private byte audienceScore;
private Person director;
private String description;
private ArrayList<Actor> actors = new ArrayList<Actor>();
private String path;
/**
* Converts a JSON response to a DTO
* @param obj The response from the server
* @param path The movie path on rotten tomatoes (not included in the JSON response)
* @throws APIRequestException If any errors were encountered while reading the response
*/
public RtMovieDTO(JSONObject obj, String path) throws APIRequestException {
try {
this.path = path;
if (obj.has("director")) {
director = new Person(obj.getJSONObject("director").getString("name"), "", obj.getJSONObject("director").getString("url"));
} else {
director = new Person("??", Person.NO_PERSON_IMAGE, "/nobody");
}
title = getString(obj, "title");
description = getString(obj, "description");
imageURL = getString(obj, "image");
score = (byte) getInt(obj.getJSONObject("score"), "critic");
audienceScore = (byte) getInt(obj.getJSONObject("score"), "audience");
actors = new ArrayList<Actor>();
for (Object o: obj.getJSONArray("cast")) {
JSONObject j = (JSONObject) o;
actors.add(new Actor(new Person(
getString(j, "name"),
getString(j, "picture"),
getString(j, "url")
), getString(j, "role")));
}
} catch(Exception e) {
System.err.println(obj.toString(2));
throw new APIRequestException("[RtMovieDTO construction] Error while constructing: " + e.getMessage(), e);
}
}
/**
* Gets Integer at field from object or -1 if non existent
* @param obj JSONObject source
* @param field The field to look at
* @return integer at field or -1
*/
private int getInt(JSONObject obj, String field) {
if (obj.has(field) && !obj.isNull(field)) {
return obj.getInt(field);
} else {
return -1;
}
}
/**
* Gets String at field from object or -1 if non existent
* @param obj JSONObject source
* @param field The field to look at
* @return integer at field or -1
*/
private String getString(JSONObject obj, String field) {
if (obj.has(field) && !obj.isNull(field)) {
return obj.getString(field);
} else {
return "";
}
}
public String getTitle() {
return title;
}
public String getImageURL() {
return imageURL;
}
public byte getScore() {
return score;
}
public byte getAudienceScore() {
return audienceScore;
}
public Person getDirector() {
return director;
}
public String getDescription() {
return description;
}
public ArrayList<Actor> getActors() {
return actors;
}
public String getPath() {
return path;
}
} |
Java | public class Main {
public static String encrypted(String value, int key) {
char[] fun = value.toCharArray();
for (int i = 0; i < value.length(); i++) {
int a = fun[i];
a = a + key;
fun[i] = (char) a;
}
value = String.valueOf(fun);
return value;
}
public static String decrypted(String value, int key) {
char[] fun = value.toCharArray();
for (int i = 0; i < value.length(); i++) {
int a = fun[i];
a = a - key;
fun[i] = (char) a;
}
value = String.valueOf(fun);
return value;
}
public static void main(String[] args) {
String value = "";
int key = 0;
String mode = "enc";
// To Find the Data
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-data")) {
if (i < args.length - 1) {
value = args[i + 1];
break;
}
}
}
// To Find the Key
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-key")) {
if (i < args.length - 1) {
key = Integer.parseInt(args[i + 1]);
}
}
}
// To Find the Mode
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-mode")) {
if (i < args.length - 1) {
if (args[i + 1].equals("enc")) {
mode = args[i + 1];
} else if (args[i + 1].equals("dec")) {
mode = args[i + 1];
}
}
}
}
// EncryptionAndDecryption
if (mode.equals("enc")) {
value = encrypted(value, key);
} else {
value = decrypted(value, key);
}
System.out.println(value);
}
} |
Java | final class Background implements Disposeable{
GLVAO m_SphereVAO;
Texture2D m_BackgroundTex;
GLFuncProvider gl;
final Matrix4f m_model = new Matrix4f();
void initlize(){
QuadricBuilder builder = new QuadricBuilder();
builder.setAutoGenNormal(false).setGenNormal(false);
builder.setXSteps(50).setYSteps(50);
builder.setPostionLocation(/*program.getAttribPosition()*/0);
builder.setTexCoordLocation(/*program.getAttribTexCoord()*/1);
builder.setDrawMode(DrawMode.FILL);
builder.setCenterToOrigin(true);
m_SphereVAO = new QuadricMesh(builder, new QuadricSphere()).getModel().genVAO();
try {
m_BackgroundTex = TextureUtils.createTexture2DFromFile("OS/textures/background.jpg", true);
} catch (IOException e) {
e.printStackTrace();
}
gl = GLFuncProviderFactory.getGLFuncProvider();
}
void draw(SingleTextureProgram program, Matrix4f projView){
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(m_BackgroundTex.getTarget(), m_BackgroundTex.getTexture());
gl.glDisable(GLenum.GL_BLEND);
m_model.setIdentity();
m_model.scale(60);
m_model.rotate((float)Math.toRadians(90), Vector3f.X_AXIS);
Matrix4f mvp = Matrix4f.mul(projView, m_model, m_model);
program.enable();
program.setMVP(mvp);
m_SphereVAO.bind();
m_SphereVAO.draw(GLenum.GL_TRIANGLES);
m_SphereVAO.unbind();
}
@Override
public void dispose() {
if(m_SphereVAO != null){
m_SphereVAO.dispose();
m_SphereVAO = null;
}
}
} |
Java | @Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.9.3"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CategoriesRecord extends UpdatableRecordImpl<CategoriesRecord> implements Record2<Integer, String> {
private static final long serialVersionUID = 1565953708;
/**
* Setter for <code>franckyi_modcenter.categories.projectId</code>.
*/
public void setProjectid(Integer value) {
set(0, value);
}
/**
* Getter for <code>franckyi_modcenter.categories.projectId</code>.
*/
public Integer getProjectid() {
return (Integer) get(0);
}
/**
* Setter for <code>franckyi_modcenter.categories.category</code>.
*/
public void setCategory(String value) {
set(1, value);
}
/**
* Getter for <code>franckyi_modcenter.categories.category</code>.
*/
public String getCategory() {
return (String) get(1);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record2<Integer, String> key() {
return (Record2) super.key();
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row2<Integer, String> fieldsRow() {
return (Row2) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row2<Integer, String> valuesRow() {
return (Row2) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return Categories.CATEGORIES.PROJECTID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return Categories.CATEGORIES.CATEGORY;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getProjectid();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getCategory();
}
/**
* {@inheritDoc}
*/
@Override
public CategoriesRecord value1(Integer value) {
setProjectid(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CategoriesRecord value2(String value) {
setCategory(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public CategoriesRecord values(Integer value1, String value2) {
value1(value1);
value2(value2);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached CategoriesRecord
*/
public CategoriesRecord() {
super(Categories.CATEGORIES);
}
/**
* Create a detached, initialised CategoriesRecord
*/
public CategoriesRecord(Integer projectid, String category) {
super(Categories.CATEGORIES);
set(0, projectid);
set(1, category);
}
} |
Java | @SuppressWarnings({"ProhibitedExceptionDeclared", "ProhibitedExceptionThrown"})
@GridCommonTest(group = "P2P")
public class GridP2PDifferentClassLoaderSelfTest extends GridCommonAbstractTest {
/**
* Class Name of task 1.
*/
private static final String TEST_TASK1_NAME = "org.gridgain.grid.tests.p2p.GridP2PTestTaskExternalPath1";
/**
* Class Name of task 2.
*/
private static final String TEST_TASK2_NAME = "org.gridgain.grid.tests.p2p.GridP2PTestTaskExternalPath2";
/**
* URL of classes.
*/
private static final URL[] URLS;
/**
* Current deployment mode. Used in {@link #getConfiguration(String)}.
*/
private GridDeploymentMode depMode;
/**
* Initialize URLs.
*/
static {
try {
URLS = new URL[] {new URL(GridTestProperties.getProperty("p2p.uri.cls"))};
}
catch (MalformedURLException e) {
throw new RuntimeException("Define property p2p.uri.cls", e);
}
}
/** {@inheritDoc} */
@Override protected GridConfiguration getConfiguration(String gridName) throws Exception {
GridConfiguration cfg = super.getConfiguration(gridName);
cfg.setDeploymentMode(depMode);
return cfg;
}
/**
* Test.
* @param isSameTask whether load same task or different task
* @param expectEquals whether expected
* @throws Exception if error occur
*/
@SuppressWarnings({"ObjectEquality", "unchecked"})
private void processTest(boolean isSameTask, boolean expectEquals) throws Exception {
try {
Grid grid1 = startGrid(1);
Grid grid2 = startGrid(2);
Class task1;
Class task2;
if (isSameTask) {
ClassLoader ldr1 = new URLClassLoader(URLS, getClass().getClassLoader());
ClassLoader ldr2 = new URLClassLoader(URLS, getClass().getClassLoader());
task1 = ldr1.loadClass(TEST_TASK1_NAME);
task2 = ldr2.loadClass(TEST_TASK1_NAME);
}
else {
ClassLoader ldr1 = new GridTestExternalClassLoader(URLS, TEST_TASK2_NAME);
ClassLoader ldr2 = new GridTestExternalClassLoader(URLS, TEST_TASK1_NAME);
task1 = ldr1.loadClass(TEST_TASK1_NAME);
task2 = ldr2.loadClass(TEST_TASK2_NAME);
}
// Execute task1 and task2 from node1 on node2 and make sure that they reuse same class loader on node2.
int[] res1 = (int[])grid1.compute().execute(task1, grid2.localNode().id()).get();
int[] res2 = (int[])grid1.compute().execute(task2, grid2.localNode().id()).get();
if (expectEquals) {
assert Arrays.equals(res1, res2);
}
else {
assert isNotSame(res1, res2);
}
}
finally {
stopGrid(1);
stopGrid(2);
}
}
/**
* Test GridDeploymentMode.PRIVATE mode.
*
* @throws Exception if error occur.
*/
public void testPrivateMode() throws Exception {
depMode = GridDeploymentMode.PRIVATE;
processTest(false, false);
}
/**
* Test GridDeploymentMode.ISOLATED mode.
*
* @throws Exception if error occur.
*/
public void testIsolatedMode() throws Exception {
depMode = GridDeploymentMode.ISOLATED;
processTest(false, false);
}
/**
* Test {@link GridDeploymentMode#CONTINUOUS} mode.
*
* @throws Exception if error occur.
*/
public void testContinuousMode() throws Exception {
depMode = GridDeploymentMode.CONTINUOUS;
processTest(false, false);
}
/**
* Test GridDeploymentMode.SHARED mode.
*
* @throws Exception if error occur.
*/
public void testSharedMode() throws Exception {
depMode = GridDeploymentMode.SHARED;
processTest(false, false);
}
/**
* Test GridDeploymentMode.PRIVATE mode.
*
* @throws Exception if error occur.
*/
public void testRedeployPrivateMode() throws Exception {
depMode = GridDeploymentMode.PRIVATE;
processTest(true, false);
}
/**
* Test GridDeploymentMode.ISOLATED mode.
*
* @throws Exception if error occur.
*/
public void testRedeployIsolatedMode() throws Exception {
depMode = GridDeploymentMode.ISOLATED;
processTest(true, false);
}
/**
* Test GridDeploymentMode.CONTINUOUS mode.
*
* @throws Exception if error occur.
*/
public void testRedeployContinuousMode() throws Exception {
depMode = GridDeploymentMode.CONTINUOUS;
processTest(true, false);
}
/**
* Test GridDeploymentMode.SHARED mode.
*
* @throws Exception if error occur.
*/
public void testRedeploySharedMode() throws Exception {
depMode = GridDeploymentMode.SHARED;
processTest(true, false);
}
/**
* Return true if and only if all elements of array are different.
*
* @param m1 array 1.
* @param m2 array 2.
* @return true if all elements of array are different.
*/
private boolean isNotSame(int[] m1, int[] m2) {
assert m1.length == m2.length;
assert m1.length == 2;
return m1[0] != m2[0] && m1[1] != m2[1];
}
} |
Java | @SuppressWarnings("serial") // Same-version serialization only
public class HyperlinkEvent extends EventObject {
/**
* Creates a new object representing a hypertext link event.
* The other constructor is preferred, as it provides more
* information if a URL could not be formed. This constructor
* is primarily for backward compatibility.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL
*/
public HyperlinkEvent(Object source, EventType type, URL u) {
this(source, type, u, null);
}
/**
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL. This may be null if a valid URL
* could not be created.
* @param desc the description of the link. This may be useful
* when attempting to form a URL resulted in a MalformedURLException.
* The description provides the text used when attempting to form the
* URL.
*/
public HyperlinkEvent(Object source, EventType type, URL u, String desc) {
this(source, type, u, desc, null);
}
/**
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL. This may be null if a valid URL
* could not be created.
* @param desc the description of the link. This may be useful
* when attempting to form a URL resulted in a MalformedURLException.
* The description provides the text used when attempting to form the
* URL.
* @param sourceElement Element in the Document representing the
* anchor
* @since 1.4
*/
public HyperlinkEvent(Object source, EventType type, URL u, String desc,
Element sourceElement) {
super(source);
this.type = type;
this.u = u;
this.desc = desc;
this.sourceElement = sourceElement;
}
/**
* Creates a new object representing a hypertext link event.
*
* @param source the object responsible for the event
* @param type the event type
* @param u the affected URL. This may be null if a valid URL
* could not be created.
* @param desc the description of the link. This may be useful
* when attempting to form a URL resulted in a MalformedURLException.
* The description provides the text used when attempting to form the
* URL.
* @param sourceElement Element in the Document representing the
* anchor
* @param inputEvent InputEvent that triggered the hyperlink event
* @since 1.7
*/
public HyperlinkEvent(Object source, EventType type, URL u, String desc,
Element sourceElement, InputEvent inputEvent) {
super(source);
this.type = type;
this.u = u;
this.desc = desc;
this.sourceElement = sourceElement;
this.inputEvent = inputEvent;
}
/**
* Gets the type of event.
*
* @return the type
*/
public EventType getEventType() {
return type;
}
/**
* Get the description of the link as a string.
* This may be useful if a URL can't be formed
* from the description, in which case the associated
* URL would be null.
*
* @return the description of this link as a {@code String}
*/
public String getDescription() {
return desc;
}
/**
* Gets the URL that the link refers to.
*
* @return the URL
*/
public URL getURL() {
return u;
}
/**
* Returns the <code>Element</code> that corresponds to the source of the
* event. This will typically be an <code>Element</code> representing
* an anchor. If a constructor that is used that does not specify a source
* <code>Element</code>, or null was specified as the source
* <code>Element</code>, this will return null.
*
* @return Element indicating source of event, or null
* @since 1.4
*/
public Element getSourceElement() {
return sourceElement;
}
/**
* Returns the {@code InputEvent} that triggered the hyperlink event.
* This will typically be a {@code MouseEvent}. If a constructor is used
* that does not specify an {@code InputEvent}, or @{code null}
* was specified as the {@code InputEvent}, this returns {@code null}.
*
* @return InputEvent that triggered the hyperlink event, or null
* @since 1.7
*/
public InputEvent getInputEvent() {
return inputEvent;
}
private EventType type;
private URL u;
private String desc;
private Element sourceElement;
private InputEvent inputEvent;
/**
* Defines the ENTERED, EXITED, and ACTIVATED event types, along
* with their string representations, returned by toString().
*/
public static final class EventType {
private EventType(String s) {
typeString = s;
}
/**
* Entered type.
*/
public static final EventType ENTERED = new EventType("ENTERED");
/**
* Exited type.
*/
public static final EventType EXITED = new EventType("EXITED");
/**
* Activated type.
*/
public static final EventType ACTIVATED = new EventType("ACTIVATED");
/**
* Converts the type to a string.
*
* @return the string
*/
public String toString() {
return typeString;
}
private String typeString;
}
} |
Java | public static final class EventType {
private EventType(String s) {
typeString = s;
}
/**
* Entered type.
*/
public static final EventType ENTERED = new EventType("ENTERED");
/**
* Exited type.
*/
public static final EventType EXITED = new EventType("EXITED");
/**
* Activated type.
*/
public static final EventType ACTIVATED = new EventType("ACTIVATED");
/**
* Converts the type to a string.
*
* @return the string
*/
public String toString() {
return typeString;
}
private String typeString;
} |
Java | public class BlockContainer extends AbstractBlock
implements Block,
Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = 8199508075695195293L;
/** The blocks within the container. */
private List blocks;
/** The object responsible for laying out the blocks. */
private Arrangement arrangement;
/**
* Creates a new instance with default settings.
*/
public BlockContainer() {
this(new BorderArrangement());
}
/**
* Creates a new instance with the specified arrangement.
*
* @param arrangement the arrangement manager (<code>null</code> not
* permitted).
*/
public BlockContainer(Arrangement arrangement) {
if (arrangement == null) {
throw new IllegalArgumentException("Null 'arrangement' argument.");
}
this.arrangement = arrangement;
this.blocks = new ArrayList();
}
/**
* Returns the arrangement (layout) manager for the container.
*
* @return The arrangement manager (never <code>null</code>).
*/
public Arrangement getArrangement() {
return this.arrangement;
}
/**
* Sets the arrangement (layout) manager.
*
* @param arrangement the arrangement (<code>null</code> not permitted).
*/
public void setArrangement(Arrangement arrangement) {
if (arrangement == null) {
throw new IllegalArgumentException("Null 'arrangement' argument.");
}
this.arrangement = arrangement;
}
/**
* Returns <code>true</code> if there are no blocks in the container, and
* <code>false</code> otherwise.
*
* @return A boolean.
*/
public boolean isEmpty() {
return this.blocks.isEmpty();
}
/**
* Returns an unmodifiable list of the {@link Block} objects managed by
* this arrangement.
*
* @return A list of blocks.
*/
public List getBlocks() {
return Collections.unmodifiableList(this.blocks);
}
/**
* Adds a block to the container.
*
* @param block the block (<code>null</code> permitted).
*/
public void add(Block block) {
add(block, null);
}
/**
* Adds a block to the container.
*
* @param block the block (<code>null</code> permitted).
* @param key the key (<code>null</code> permitted).
*/
public void add(Block block, Object key) {
this.blocks.add(block);
this.arrangement.add(block, key);
}
/**
* Clears all the blocks from the container.
*/
public void clear() {
this.blocks.clear();
this.arrangement.clear();
}
/**
* Arranges the contents of the block, within the given constraints, and
* returns the block size.
*
* @param g2 the graphics device.
* @param constraint the constraint (<code>null</code> not permitted).
*
* @return The block size (in Java2D units, never <code>null</code>).
*/
public Size2D arrange(Graphics2D g2, RectangleConstraint constraint) {
return this.arrangement.arrange(this, g2, constraint);
}
/**
* Draws the container and all the blocks within it.
*
* @param g2 the graphics device.
* @param area the area.
*/
public void draw(Graphics2D g2, Rectangle2D area) {
draw(g2, area, null);
}
/**
* Draws the block within the specified area.
*
* @param g2 the graphics device.
* @param area the area.
* @param params passed on to blocks within the container
* (<code>null</code> permitted).
*
* @return An instance of {@link EntityBlockResult}, or <code>null</code>.
*/
public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
// check if we need to collect chart entities from the container
EntityBlockParams ebp = null;
StandardEntityCollection sec = null;
if (params instanceof EntityBlockParams) {
ebp = (EntityBlockParams) params;
if (ebp.getGenerateEntities()) {
sec = new StandardEntityCollection();
}
}
Rectangle2D contentArea = (Rectangle2D) area.clone();
contentArea = trimMargin(contentArea);
drawBorder(g2, contentArea);
contentArea = trimBorder(contentArea);
contentArea = trimPadding(contentArea);
Iterator iterator = this.blocks.iterator();
while (iterator.hasNext()) {
Block block = (Block) iterator.next();
Rectangle2D bounds = block.getBounds();
Rectangle2D drawArea = new Rectangle2D.Double(bounds.getX()
+ area.getX(), bounds.getY() + area.getY(),
bounds.getWidth(), bounds.getHeight());
Object r = block.draw(g2, drawArea, params);
if (sec != null) {
if (r instanceof EntityBlockResult) {
EntityBlockResult ebr = (EntityBlockResult) r;
EntityCollection ec = ebr.getEntityCollection();
sec.addAll(ec);
}
}
}
BlockResult result = null;
if (sec != null) {
result = new BlockResult();
result.setEntityCollection(sec);
}
return result;
}
/**
* Tests this container for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof BlockContainer)) {
return false;
}
if (!super.equals(obj)) {
return false;
}
BlockContainer that = (BlockContainer) obj;
if (!this.arrangement.equals(that.arrangement)) {
return false;
}
if (!this.blocks.equals(that.blocks)) {
return false;
}
return true;
}
/**
* Returns a clone of the container.
*
* @return A clone.
*
* @throws CloneNotSupportedException if there is a problem cloning.
*/
public Object clone() throws CloneNotSupportedException {
BlockContainer clone = (BlockContainer) super.clone();
// TODO : complete this
return clone;
}
} |
Java | public class IndexConfiguration {
private String name;
private String index;
private String type;
private boolean cache;
private long expire;
private List<String> cluster = new ArrayList<>();
private int port;
private IndexBulkConfiguration bulk;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public List<String> getCluster() {
return cluster;
}
public void setCluster(List<String> cluster) {
this.cluster = cluster;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public IndexBulkConfiguration getBulk() {
return bulk;
}
public void setBulk(IndexBulkConfiguration bulk) {
this.bulk = bulk;
}
public boolean isCache() {
return cache;
}
public void setCache(boolean cache) {
this.cache = cache;
}
public long getExpire() {
return expire;
}
public void setExpire(long expire) {
this.expire = expire;
}
@Override
public String toString() {
return "IndexConfiguration{" +
"name='" + name + '\'' +
", index='" + index + '\'' +
", type='" + type + '\'' +
", cache=" + cache +
", expire=" + expire +
", cluster=" + cluster +
", port=" + port +
", bulk=" + bulk +
'}';
}
} |
Java | public class ProxyFactoryTests {
private final Object target = new Object();
@Test
public void newProxyFactoryIsNotNull() {
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getMethodInterceptors()).isEmpty();
assertThat(proxyFactory.getProxyClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
assertThat(proxyFactory.getProxyInterfaces()).isEmpty();
assertThat(proxyFactory.getTarget()).isNull();
}
@Test
public void newProxyFactoryForTargetObjectAndInterfaces() {
Contact johnBlum = Contact.newContact("John Blum");
ProxyFactory<Object> proxyFactory = newProxyFactory(johnBlum, Auditable.class, Identifiable.class, Runnable.class);
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getMethodInterceptors()).isEmpty();
assertThat(proxyFactory.getProxyClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
assertThat(proxyFactory.getProxyInterfaces()).contains(Auditable.class, Identifiable.class, Runnable.class);
assertThat(proxyFactory.getTarget()).isEqualTo(johnBlum);
}
@Test
public void resolvesGivenInterfaces() {
assertThat(ProxyFactory.resolveInterfaces(Contact.newContact("John Blum"), Auditable.class, Identifiable.class))
.contains(Auditable.class, Identifiable.class);
}
@Test
public void resolvesImplementingInterfaces() {
assertThat(ProxyFactory.resolveInterfaces(mock(Golfer.class)))
.contains(Auditable.class, Comparable.class, Identifiable.class, Serializable.class);
}
@Test
public void resolvesImplementingAndProvidedInterfaces() {
assertThat(ProxyFactory.resolveInterfaces(mock(Golfer.class), Runnable.class))
.contains(Auditable.class, Comparable.class, Identifiable.class, Runnable.class, Serializable.class);
}
@Test
public void resolvesNoInterfaces() {
assertThat(ProxyFactory.resolveInterfaces(Contact.newContact("John Blum"))).isEmpty();
assertThat(ProxyFactory.resolveInterfaces(new Object())).isEmpty();
}
@Test
@SuppressWarnings("unchecked")
public void adviseWithMethodInterceptors() {
MethodInterceptor mockMethodInterceptorOne = mock(MethodInterceptor.class);
MethodInterceptor mockMethodInterceptorTwo = mock(MethodInterceptor.class);
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getMethodInterceptors()).isEmpty();
assertThat(proxyFactory.adviseWith(mockMethodInterceptorOne, mockMethodInterceptorTwo)).isSameAs(proxyFactory);
assertThat(proxyFactory.getMethodInterceptors()).contains(mockMethodInterceptorOne, mockMethodInterceptorTwo);
}
@Test
public void adviseWithNullMethodInterceptors() {
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getMethodInterceptors()).isEmpty();
assertThat(proxyFactory.adviseWith((MethodInterceptor<Object>[]) null)).isSameAs(proxyFactory);
assertThat(proxyFactory.getMethodInterceptors()).isEmpty();
}
@Test
public void implementingInterfaces() {
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getProxyInterfaces()).isEmpty();
assertThat(proxyFactory.implementing(Auditable.class, Identifiable.class)).isSameAs(proxyFactory);
assertThat(proxyFactory.getProxyInterfaces()).contains(Auditable.class, Identifiable.class);
}
@Test
public void implementingNoInterfaces() {
ProxyFactory<Object> proxyFactory = newProxyFactory(target, Auditable.class, Identifiable.class);
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getProxyInterfaces()).contains(Auditable.class, Identifiable.class);
assertThat(proxyFactory.getTarget()).isSameAs(target);
assertThat(proxyFactory.implementing((Class[]) null)).isSameAs(proxyFactory);
assertThat(proxyFactory.getProxyInterfaces()).isEmpty();
assertThat(proxyFactory.getTarget()).isSameAs(target);
}
@Test
public void proxyTarget() {
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getTarget()).isNull();
assertThat(proxyFactory.proxy(target)).isSameAs(proxyFactory);
assertThat(proxyFactory.getTarget()).isSameAs(target);
}
@Test
public void proxyNull() {
ProxyFactory<Object> proxyFactory = newProxyFactory(target);
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getTarget()).isSameAs(target);
assertThat(proxyFactory.proxy(null)).isSameAs(proxyFactory);
assertThat(proxyFactory.getTarget()).isNull();
}
@Test
public void usingSystemClassLoader() {
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.getProxyClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
assertThat(proxyFactory.using(ClassLoader.getSystemClassLoader())).isSameAs(proxyFactory);
assertThat(proxyFactory.getProxyClassLoader()).isEqualTo(ClassLoader.getSystemClassLoader());
}
@Test
public void usingThreadContextClassLoader() {
ProxyFactory<Object> proxyFactory = newProxyFactory();
assertThat(proxyFactory).isNotNull();
assertThat(proxyFactory.using(null)).isSameAs(proxyFactory);
assertThat(proxyFactory.getProxyClassLoader()).isEqualTo(Thread.currentThread().getContextClassLoader());
}
abstract class Entity implements Auditable {
}
abstract class Person extends Entity implements Comparable<Person>, Serializable {
}
abstract class Golfer extends Person {
}
@Data
@RequiredArgsConstructor(staticName = "newContact")
static class Contact {
@NonNull String name;
}
} |
Java | public class CalloutDecorator implements ScreenshotDecorator {
private String number;
private DecoratorLayout layout;
private int diameter;
private Font font;
private int borderThickness;
public CalloutDecorator(int number)
{
this(number, 34, new Center());
}
public CalloutDecorator(int number, DecoratorLayout layout)
{
this(number, 34, layout);
}
public CalloutDecorator(int number, int diameter)
{
this(number, diameter, new Center());
}
public CalloutDecorator(int number, int diameter, DecoratorLayout layout)
{
super();
this.number = number + "";
this.layout = layout;
this.diameter = Math.max(diameter, 12);
borderThickness = Math.max((int) Math.round(diameter * 0.1), 1);
float fontSizeFactor = (number > 9) ? 0.55f : 0.65f;
font = new Font("SansSerif", Font.PLAIN, (int) (diameter * fontSizeFactor));
}
public Rectangle2D getBounds(JComponent component, JComponent rootComponent)
{
Point2D position = layout.getPosition(component, rootComponent);
double radie = diameter/2.0;
return new Rectangle2D.Double(position.getX() - radie, position.getY() - radie, diameter, diameter);
}
@Override
public void paint(Graphics2D g2d, JComponent component, JComponent rootComponent)
{
AffineTransform at = g2d.getTransform();
double radie = diameter/2.0;
Point2D position = layout.getPosition(component, rootComponent);
g2d.translate(position.getX() - radie, position.getY() - radie);
Ellipse2D circle = new Ellipse2D.Float(0, 0, diameter, diameter);
g2d.setColor(Color.WHITE);
g2d.fill(circle);
g2d.translate(borderThickness, borderThickness);
circle.setFrame(0, 0, circle.getWidth() - borderThickness * 2, circle.getHeight() - borderThickness * 2);
g2d.setColor(Color.BLACK);
g2d.fill(circle);
g2d.translate(-borderThickness, -borderThickness);
g2d.setColor(Color.WHITE);
g2d.setFont(font);
drawCenteredText(g2d, number);
g2d.setTransform(at);
}
private void drawCenteredText(Graphics2D g2d, String text)
{
Rectangle2D bounds = getTextBounds(g2d, text);
float radie = (float) (diameter/2.0);
g2d.drawString(text, (float)(radie - bounds.getCenterX()), (float) (radie - bounds.getCenterY()));
}
private Rectangle2D getTextBounds(Graphics2D g, String text)
{
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle2D bounds = fontMetrics.getStringBounds(text, g);
return bounds;
}
} |
Java | public class Cam extends DragonflyDomain implements Comparable<Cam>
{
public static final String root = "cam";
public static final String parent = "webcam";
public Cam()
{
super();
}
@Exportable(xmlName = "handle")
public String handle;
@Exportable(xmlName = "camid")
public String camid;
@Exportable(xmlName = "camindex")
public String camindex;
@Exportable(xmlName = "type")
public String type;
@Exportable(xmlName = "assoc_station_id", jsonName = "assocStationId")
public String assocStationId;
@Exportable(xmlName = "link")
public String link;
@Exportable(xmlName = "linktext")
public String linktext;
@Exportable(xmlName = "cameratype")
public String cameratype;
@Exportable(xmlName = "organization")
public String organization;
@Exportable(xmlName = "neighborhood")
public String neighborhood;
@Exportable(xmlName = "address")
public String address;
@Exportable(xmlName = "zip")
public String zip;
@Exportable(xmlName = "city")
public String city;
@Exportable(xmlName = "state")
public String state;
@Exportable(xmlName = "country")
public String country;
@Exportable(xmlName = "tzname")
public String tzname;
@Exportable(xmlName = "hexant")
public String hexant;
@Exportable(xmlName = "hexid")
public String hexid;
@Exportable(xmlName = "lat")
public String lat;
@Exportable(xmlName = "lon")
public String lon;
@Exportable(xmlName = "updated")
public String updated;
@Exportable(xmlName = "downloaded")
public String downloaded;
@Exportable(xmlName = "hash")
public String hash;
@Exportable(xmlName = "isrecent")
public String isrecent;
@Exportable(xmlName = "frequency")
public String frequency;
@Exportable(xmlName = "CURRENTIMAGEURL", jsonName = "currentImageUrl")
public String currentImageUrl;
@Exportable(xmlName = "WIDGETCURRENTIMAGEURL", jsonName = "widgitCurrentImageUrl")
public String widgitCurrentImageUrl;
@Exportable(xmlName = "CAMURL", jsonName = "camUrl")
public String camUrl;
@Override
public int compareTo(Cam o)
{
// TODO Auto-generated method stub
return 0;
}
public String getHandle()
{
return handle;
}
public void setHandle(String handle)
{
this.handle = handle;
}
public String getCamid()
{
return camid;
}
public void setCamid(String camid)
{
this.camid = camid;
}
public String getCamindex()
{
return camindex;
}
public void setCamindex(String camindex)
{
this.camindex = camindex;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public String getAssocStationId()
{
return assocStationId;
}
public void setAssocStationId(String assocStationId)
{
this.assocStationId = assocStationId;
}
public String getLink()
{
return link;
}
public void setLink(String link)
{
this.link = link;
}
public String getLinktext()
{
return linktext;
}
public void setLinktext(String linktext)
{
this.linktext = linktext;
}
public String getCameratype()
{
return cameratype;
}
public void setCameratype(String cameratype)
{
this.cameratype = cameratype;
}
public String getOrganization()
{
return organization;
}
public void setOrganization(String organization)
{
this.organization = organization;
}
public String getNeighborhood()
{
return neighborhood;
}
public void setNeighborhood(String neighborhood)
{
this.neighborhood = neighborhood;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getZip()
{
return zip;
}
public void setZip(String zip)
{
this.zip = zip;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getTzname()
{
return tzname;
}
public void setTzname(String tzname)
{
this.tzname = tzname;
}
public String getHexant()
{
return hexant;
}
public void setHexant(String hexant)
{
this.hexant = hexant;
}
public String getHexid()
{
return hexid;
}
public void setHexid(String hexid)
{
this.hexid = hexid;
}
public String getLat()
{
return lat;
}
public void setLat(String lat)
{
this.lat = lat;
}
public String getLon()
{
return lon;
}
public void setLon(String lon)
{
this.lon = lon;
}
public String getUpdated()
{
return updated;
}
public void setUpdated(String updated)
{
this.updated = updated;
}
public String getDownloaded()
{
return downloaded;
}
public void setDownloaded(String downloaded)
{
this.downloaded = downloaded;
}
public String getHash()
{
return hash;
}
public void setHash(String hash)
{
this.hash = hash;
}
public String getIsrecent()
{
return isrecent;
}
public void setIsrecent(String isrecent)
{
this.isrecent = isrecent;
}
public String getFrequency()
{
return frequency;
}
public void setFrequency(String frequency)
{
this.frequency = frequency;
}
public String getCurrentImageUrl()
{
return currentImageUrl;
}
public void setCurrentImageUrl(String currentImageUrl)
{
this.currentImageUrl = currentImageUrl;
}
public String getWidgitCurrentImageUrl()
{
return widgitCurrentImageUrl;
}
public void setWidgitCurrentImageUrl(String widgitCurrentImageUrl)
{
this.widgitCurrentImageUrl = widgitCurrentImageUrl;
}
public String getCamUrl()
{
return camUrl;
}
public void setCamUrl(String camUrl)
{
this.camUrl = camUrl;
}
} |
Java | @Component
@FluflCommand
@CommandLine.Command(name ="list-history")
public class ListHistorySubCommand implements Runnable {
private FlowableService flowableService;
@Override
public void run() {
System.out.println(flowableService.listHistory());
}
@Autowired
public void setFlowableService(FlowableService flowableService) {
this.flowableService = flowableService;
}
} |
Java | public class EncryptedApplicationPayloadBuilder extends BaseEncryptedApplicationPayloadBuilder<EncryptedApplicationPayloadBuilder, IEncryptedApplicationPayload, EncryptedApplicationPayload.Builder>
{
EncryptedApplicationPayloadBuilder(IAllegroApi cryptoClient)
{
super(EncryptedApplicationPayloadBuilder.class, new EncryptedApplicationPayload.Builder(), cryptoClient);
}
/**
* Set the id of the thread with whose content key this object will be encrypted.
*
* @param threadId The id of the thread with whose content key this object will be encrypted.
*
* @return This (fluent method).
*/
public EncryptedApplicationPayloadBuilder withThreadId(ThreadId threadId)
{
builder_.withThreadId(threadId);
return self();
}
@Override
protected IEncryptedApplicationPayload construct()
{
return builder_.build();
}
} |
Java | @Unscoped
public class UndertowBlockingHandler extends RequestProcessor<HttpServerExchange> implements HttpHandler {
private final ActionResolution resolution;
@Inject
public UndertowBlockingHandler(@Message ActionResolution resolution, ThreadScope threadScope, Router router, ErrorHandler errorHandler) {
super(threadScope, router, errorHandler);
this.resolution = resolution;
}
@Override
protected HttpRequest createHttpRequest(HttpServerExchange exchange) {
return new HttpRequestImpl(exchange);
}
@Override
protected HttpResponse createHttpResponse(HttpServerExchange exchange) {
return new HttpResponseImpl(exchange);
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
performAction(resolution, exchange);
exchange.endExchange();
}
} |
Java | @JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class LineageRelationshipEvent extends AssetLineageEventHeader {
private LineageRelationship lineageRelationship;
/**
* Gets lineage relationship.
*
* @return the lineage relationship
*/
public LineageRelationship getLineageRelationship() {
return lineageRelationship;
}
/**
* Sets lineage relationship.
*
* @param lineageRelationship the lineage relationship
*/
public void setLineageRelationship(LineageRelationship lineageRelationship) {
this.lineageRelationship = lineageRelationship;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LineageRelationshipEvent that = (LineageRelationshipEvent) o;
return Objects.equals(lineageRelationship, that.lineageRelationship);
}
@Override
public int hashCode() {
return Objects.hash(lineageRelationship);
}
@Override
public String toString() {
return "LineageRelationshipEvent{" +
"lineageRelationship=" + lineageRelationship +
'}';
}
} |
Java | public final class Permutation implements Comparable<Permutation>, Serializable {
// statics
static final long serialVersionUID = -9053863703146584610L;
private static final int[] NO_CYCLES = {};
private static void verifyRange(int[] correspondence) {
for (int i = 0; i < correspondence.length; i++) {
int c = correspondence[i];
if (c < 0 || c >= correspondence.length) throw new IllegalArgumentException("invalid correspondence");
}
}
private static void verifyUnique(int size, int[] indices) {
SortedSet<Integer> check = Bits.store(size).ones().asSet();
for (int i : indices) {
boolean result;
try {
result = check.add(i);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("cycle contains invalid index: " + i);
}
if (!result) throw new IllegalArgumentException("cycle contains duplicate index: " + i);
}
}
private static int[] computeIdentity(int[] correspondence) {
for (int i = 0; i < correspondence.length; i++) {
correspondence[i] = i;
}
return correspondence;
}
private static int[] computeInverse(int[] correspondence) {
int[] array = new int[correspondence.length];
for (int i = 0; i < array.length; i++) {
array[correspondence[i]] = i;
}
return array;
}
private static int[] computeCycles(int[] correspondence) {
int[] array = correspondence.clone();
int[] cycles = new int[array.length + 1];
int index = 0;
outer: while (true) {
for (int i = 0; i < array.length; i++) {
int a = array[i];
if (a == -1) {
continue;
}
if (a == i) {
array[i] = -1;
continue;
}
for (int j = i;;) {
int b = array[j];
if (b == -1) throw new IllegalArgumentException("invalid correspondence");
array[j] = -1;
if (b == i) {
cycles[index++] = -1 - b;
break;
}
cycles[index++] = b;
j = b;
}
continue outer;
}
break;
}
return cycles.length > index ? Arrays.copyOf(cycles, index) : cycles;
}
private static void computeShuffle(int[] array, Random random) {
for (int i = array.length - 1; i > 0 ; i--) {
int j = random.nextInt(i + 1);
int t = array[i];
array[i] = array[j];
array[j] = t;
}
}
private static void checkSize(int size) {
if (size < 0) throw new IllegalArgumentException("negative size");
}
/**
* Creates an identity permutation of a given size. The identity permutation
* does perform any reordering of indexed values.
*
* @param size
* the size of the permutation
* @return an identity permutation
*/
public static Permutation identity(int size) {
checkSize(size);
int[] correspondence = new int[size];
computeIdentity(correspondence);
return new Permutation(correspondence, NO_CYCLES);
}
/**
* Creates a permutation that reverses the order of indexed values. Applying
* the permutation twice will leave all values at their original positions.
*
* @param size
* the size of the permutation
* @return a reverse permutation
*/
public static Permutation reverse(int size) {
checkSize(size);
int[] correspondence = new int[size];
for (int i = 0; i < size; i++) {
correspondence[i] = size - i - 1;
}
int h = size / 2;
int[] cycles = new int[h * 2];
for (int i = 0, j = 0; i < h; i++) {
cycles[j++] = i;
cycles[j++] = i - size;
}
return new Permutation(correspondence, cycles);
}
/**
* Creates a rotation permutation which changes the index of each value by a
* fixed amount (the distance) which is added to the value's original index.
* The specified distance may be negative and may exceed the size, though
* only <i>size</i> distinct rotations are possible.
*
* @param size
* the size of the permutation
* @param distance
* the amount by which a value's index is increased.
* @return a rotation permutation
*/
public static Permutation rotate(int size, int distance) {
checkSize(size);
if (size < 2) return identity(size);
distance = -distance % size;
if (distance == 0) return identity(size);
int[] correspondence = new int[size];
if (distance < 0) distance += size;
//TODO lazy, remove repeated %
for (int i = 0; i < size; i++) {
correspondence[i] = (i + distance) % size;
}
int[] cycles = new int[size];
for (int i = 0, j = i, c = correspondence[j]; c != 0; i++, j = c, c = correspondence[j]) {
cycles[i] = c;
}
cycles[size - 1] = -1 - cycles[size - 1];
return new Permutation(correspondence, cycles);
}
/**
* Creates a permutation that swaps two values.
*
* @param size
* the size of the permutation
* @param i
* an index in the range [0,size)
* @param j
* an index in the range [0,size) which is not equal to i
* @return a transposition
*/
public static Permutation transpose(int size, int i, int j) {
checkSize(size);
if (i < 0 || j < 0 || i >= size || j >= size) throw new IllegalArgumentException("invalid indices");
if (i == j) return identity(size);
int[] correspondence = new int[size];
computeIdentity(correspondence);
correspondence[i] = j;
correspondence[j] = i;
int[] cycles = {i, -1 - j };
return new Permutation(correspondence, cycles);
}
/**
* <p>
* Creates a permutation that shifts values through a specified cycle of
* indices such that the value at index <code>cycle[0]</code> will move to
* index <code>cycle[1]</code>; in general the value at index
* <code>cycle[i]</code> moving to index <code>cycle[i+1]</code> with the
* final value at <code>cycle[length-1]</code> moving to index
* <code>cycle[0]</code>.
*
* <p>
* It is permitted for the supplied cycle array may be empty, or of length
* 1, in which case the generated permutation will be the identity
* permutation of the given size. The indices in the cycle array must be
* valid (ie. lie in the range [0..size) ). The cycle array must form a
* valid cycle and thus may not contain duplicates.
*
* @param size
* the size of the permutation
* @param cycle
* the indices through which permuted values should be cycled
* @return a cyclic permutation, or possibly the identity permutation
*/
public static Permutation cycle(int size, int... cycle) {
checkSize(size);
if (cycle == null) throw new IllegalArgumentException("null cycle");
int length = cycle.length;
if (length > size) throw new IllegalArgumentException("cycle larger than permutation");
switch (length) {
case 0:
// nothing to do
return identity(size);
case 1: {
// just check argument
int i = cycle[0];
if (i < 0) throw new IllegalArgumentException("negative index: " + i);
if (i >= size) throw new IllegalArgumentException("index too large: " + i);
return identity(size);
}
case 2: {
int i = cycle[0];
int j = cycle[1];
// check for dupes...
if (i == j) throw new IllegalArgumentException("cycle contains duplicate index: " + i);
// ... otherwise treat as a transposition
return transpose(size, i, j);
}
default:
// check for dupes in cycle
verifyUnique(size, cycle);
// now start cycling
int[] correspondence = new int[size];
computeIdentity(correspondence);
int target = cycle[0];
int t = correspondence[target];
for (int i = 1; i < length; i++) {
int source = cycle[i];
correspondence[target] = correspondence[source];
target = source;
}
correspondence[target] = t;
int[] cycles = cycle.clone();
cycles[length - 1] = -1 - target;
return new Permutation(correspondence, cycles);
}
}
/**
* Creates a permutation that randomly shuffles values to new indices. The
* generated permutation is wholly determined by the state of the random
* generator supplied to the method.
*
* @param size
* the size of the permutation
* @param random
* a source of random numbers
* @return a shuffling permutation
*/
public static Permutation shuffle(int size, Random random) {
checkSize(size);
if (random == null) throw new IllegalArgumentException("null random");
int[] correspondence = new int[size];
computeIdentity(correspondence);
computeShuffle(correspondence, random);
Arrays.toString(correspondence);
return new Permutation(correspondence, null);
}
/**
* Specifies a permutation via a correspondence. This method is capable of
* creating any possible permutation. The size of the permutation will equal
* the length of the supplied array. The array must contain, in any order,
* each integer from zero to <code>length-1</code> exactly once. The
* resulting permutation will be such that the value at index <code>i</code>
* will have originated from index <code>correspondence[i]</code>
*
* @param correspondence
* the correspondence array
* @return a permutation with the specified correspondence.
* @see #reorder(int...)
*/
public static Permutation correspond(int... correspondence) {
if (correspondence == null) throw new IllegalArgumentException("null correspondence");
verifyRange(correspondence);
int[] cycles = computeCycles(correspondence);
return new Permutation(correspondence.clone(), cycles);
}
/**
* <p>
* Specifies a permutation via a reordering. This method is capable of
* creating any possible permutation. The size of the permutation will equal
* the length of the supplied array. The array must contain, in any order,
* each integer from zero to <code>length-1</code> exactly once. The
* resulting permutation will be such that the value at index
* <code>correspondence[i]</code> will have originated from index
* <code>i</code>.
*
* <p>
* This method of constructing permutations is the inverse of the
* {@link #correspond(int...)} method in the sense that the permutations
* created by <code>Permutation.correspond(array)</code> and
* <code>Permutation.reorder(array)</code> are inverse.
*
* @param ordering
* a reordering of indices
* @return a permutation that will reorder the supplied array
* @see #correspond(int...)
*/
public static Permutation reorder(int... ordering) {
if (ordering == null) throw new IllegalArgumentException("null ordering");
int[] correspondence;
try {
correspondence = computeInverse(ordering);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid ordering");
}
int[] cycles = computeCycles(correspondence);
return new Permutation(correspondence, cycles);
}
// fields
private final int[] correspondence;
//cycles is so important, we keep that on permutation
private int[] cycles = null;
//everything else is secondary, and we store it separately
private Info info = null;
// constructors
private Permutation(int[] correspondence, int[] cycles) {
this.correspondence = correspondence;
this.cycles = cycles;
}
Permutation(Generator generator) {
this.correspondence = generator.correspondence.clone();
}
// accessors
/**
* The size of the permutation. This is the number of indices over which the
* permutation can operate.
*
* @return the size of the permutation.
*/
public int size() {
return correspondence.length;
}
/**
* The correspondence between pre and post permutation indices. This array
* completely determines the effect of the permutation which will operate
* such that the value at index <code>correspondence[i]</code> will be moved
* to <code>i</code>. The length of the array will always match the size of
* the permutation.
*
* @return the correspondence for the permutation
* @see #correspond(int...)
* @see #size()
*/
public int[] correspondence() {
return correspondence.clone();
}
/**
* Information about the permutation beyond its size and correspondence.
*
* @return information about the permutation
*/
public Info info() {
return info == null ? info = new Info() : info;
}
// public methods
/**
* <p>
* A convenient method for generating a permutation that is the inverse of
* this permutation.
*
* <p>
* This is logically equivalent to calling
* <code>p.generator().invert().permutation()</code>.
*
* @return the inverse permutation.
*/
public Permutation inverse() {
//TODO should derive cycles
return new Permutation(computeInverse(correspondence), null);
}
/**
* Creates a new permutation generator initialized with this permutation.
*
* @return a new permutation generator
*/
public Generator generator() {
return new Generator(correspondence.clone());
}
/**
* Permutes an object by transposing its elements. Permutations are applied
* to objects by repeatedly swapping elements until the value order has been
* changed to match the permutation. The <code>Transposable</code> interface
* provides the means by which these swaps are executed on the object.
*
* @param transposable
* an object whose values may be transposed
*/
public void permute(Transposable transposable) {
if (transposable == null) throw new IllegalArgumentException("null transposable");
int[] cycles = getCycles();
for (int i = 0, initial = -1, previous = -1; i < cycles.length; i++) {
int next = cycles[i];
if (initial < 0) {
initial = next;
} else {
if (next < 0) {
next = -1 - next;
initial = -1;
}
transposable.transpose(previous, next);
}
previous = next;
}
}
/**
* Permutes an object using the inverse of this permutation.
*
* @param transposable
* an object whose values may be transposed
*
* @see #inverse()
* @see #permute(Transposable)
*/
public void unpermute(Transposable transposable) {
if (transposable == null) throw new IllegalArgumentException("null transposable");
int[] cycles = getCycles();
int length = cycles.length;
if (length == 0) return;
for (int i = length - 2, previous = -1 - cycles[length - 1], initial = previous; i >= 0; i--) {
int next = cycles[i];
if (next < 0) {
initial = -1 - next;
previous = initial;
} else {
transposable.transpose(previous, next);
previous = next;
}
}
}
// comparable methods
/**
* Permutations are ordered first by size (smaller sizes precede larger
* sizes) and then by their correspondence arrays (in the natural order
* induced by their elements).
*/
@Override
public int compareTo(Permutation that) {
if (this == that) return 0;
int thisSize = this.correspondence.length;
int thatSize = that.correspondence.length;
if (thisSize < thatSize) return -1;
if (thisSize > thatSize) return 1;
int[] thisArray = this.correspondence;
int[] thatArray = that.correspondence;
for (int i = 0; i < thisSize; i++) {
int c = thisArray[i] - thatArray[i];
if (c == 0) continue;
return c;
}
return 0;
}
// object methods
@Override
public int hashCode() {
return Arrays.hashCode(correspondence);
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Permutation)) return false;
Permutation that = (Permutation) obj;
return Arrays.equals(this.correspondence, that.correspondence);
}
@Override
public String toString() {
return Arrays.toString(correspondence);
}
// package scoped methods
void generator(Generator generator) {
System.arraycopy(this.correspondence, 0, generator.correspondence, 0, this.correspondence.length);
}
// serialization methods
private Object writeReplace() throws ObjectStreamException {
return new Serial(correspondence);
}
// private utility methods
private int[] getCycles() {
if (cycles == null) {
cycles = computeCycles(correspondence);
}
return cycles;
}
// innner classes
private static class Serial implements Serializable {
private static final long serialVersionUID = -8684974003295220000L;
int[] correspondence;
Serial(int[] correspondence) {
this.correspondence = correspondence;
}
private Object readResolve() throws ObjectStreamException {
return Permutation.correspond(correspondence);
}
}
/**
* Provides information about a permutation
*
* @author Tom Gibara
*/
public final class Info {
private final static int BIT_GET_REVERSAL = 0;
private final static int BIT_SET_REVERSAL = 1;
private final static int BIT_GET_ROTATION = 2;
private final static int BIT_SET_ROTATION = 3;
private final static int MSK_GET_REVERSAL = 1 << BIT_GET_REVERSAL;
private final static int MSK_SET_REVERSAL = 1 << BIT_SET_REVERSAL;
private final static int MSK_GET_ROTATION = 1 << BIT_GET_ROTATION;
private final static int MSK_SET_ROTATION = 1 << BIT_SET_ROTATION;
// computed eagerly
private final int numberOfCycles;
private final int numberOfTranspositions;
// computed lazily
private short flags = 0;
private BitStore fixedPoints;
private Set<Permutation> disjointCycles;
private BigInteger lengthOfOrbit;
Info() {
// ensure number of cycles has been computed
// set properties that are cheap, eagerly
int numberOfCycles = 0;
int[] cycles = getCycles();
for (int i = 0; i < cycles.length; i++) {
if (cycles[i] < 0) numberOfCycles++;
}
this.numberOfCycles = numberOfCycles;
numberOfTranspositions = cycles.length - numberOfCycles;
}
/**
* The permutation about which information is being provided.
*
* @return the permutation
*/
public Permutation getPermutation() {
return Permutation.this;
}
/**
* The number of disjoint cycles. All permutations can be decomposed
* into a set of disjoint cycles.
*
* @return the number of cycles
* @see #getDisjointCycles()
*/
public int getNumberOfCycles() {
return numberOfCycles;
}
/**
* The number of transpositions made by the permutation. All
* permutations are applied as a sequence of transpositions.
*
* @return the number of transpositions
*/
public int getNumberOfTranspositions() {
return numberOfTranspositions;
}
/**
* Whether the permutation makes no changes to the indexing of values.
*
* @return whether the permutation is the identity permutation
*/
public boolean isIdentity() {
return numberOfTranspositions == 0;
}
/**
* Whether the permutation consists of an odd number of transpositions.
*
* @return whether the permutation is odd
*/
public boolean isOdd() {
return (numberOfTranspositions & 1) == 1;
}
/**
* Whether the permutation consists of a single transposition.
*
* @return whether the permutation is a transposition
* @see Permutation#transpose(int, int, int)
*/
public boolean isTransposition() {
return numberOfTranspositions == 1;
}
/**
* Whether the permutation reverses the indexing of values.
*
* @return whether the permutation is a reversal
* @see Permutation#reverse(int)
*/
public boolean isReversal() {
int m = MSK_SET_REVERSAL | MSK_GET_REVERSAL;
int bits = flags & m;
if (bits != 0) return bits == m;
boolean f = isReversalImpl();
flags |= f ? m : MSK_SET_REVERSAL;
return f;
}
private boolean isReversalImpl() {
int len = correspondence.length - 1;
for (int i = 0; i <= len; i++) {
if (correspondence[i] != len - i) return false;
}
return true;
}
/**
* Whether the permutation consists of a single cycle.
*
* @return whether the permutation is cyclic.
* @see Permutation#cycle(int, int...)
*/
public boolean isCyclic() {
return numberOfCycles == 1;
}
/**
* Whether the permutation is a rotation.
*
* @return whether the permutation is a rotation
* @see Permutation#rotate(int, int)
*/
public boolean isRotation() {
int m = MSK_SET_ROTATION | MSK_GET_ROTATION;
int bits = flags & m;
if (bits != 0) return bits == m;
boolean f = isRotationImpl();
flags |= f ? m : MSK_SET_ROTATION;
return f;
}
private boolean isRotationImpl() {
int length = correspondence.length;
if (length < 3) return true;
if (isIdentity()) return true;
int e = correspondence[0];
for (int i = 0; i < length; i++) {
if (correspondence[i] != e) return false;
e++;
if (e == length) e -= length;
}
return true;
}
/**
* Optionally, the distance through which the permutation rotates
* values. The rotation distance of any identity permutation is zero.
*
* @return the distance of rotation, or empty if the permutation is not
* a rotation
* @see Permutation#rotate(int, int)
*/
public Optional<Integer> rotationDistance() {
if (isIdentity()) return Optional.of(0);
if (isRotation()) return Optional.of(correspondence.length - correspondence[0]);
return Optional.empty();
}
/**
* <p>
* An immutable bit store indicating the positions at which values
* remain untouched by the permutation. That is:
* <code>p.info().getFixedPoints().getBit(i)</code> is true iff
* <code>p.correspondence()[i] == i</code>
*
* <p>
* Note that the supplied bits can be viewed as a set of integer
* positions using: <code>p.info().getFixedPoints().asSet()</code>
*
* @return bits the positions that are fixed by the permutation.
*/
public BitStore getFixedPoints() {
if (fixedPoints == null) {
int[] array = correspondence;
fixedPoints = Bits.store(array.length);
for (int i = 0; i < array.length; i++) {
if (array[i] == i) fixedPoints.setBit(i, true);
}
fixedPoints = fixedPoints.immutableCopy();
}
return fixedPoints;
}
/**
* The disjoint cycles of the permutation. Each permutation in the
* returned set is cyclic and no two permutations will transpose values
* at the same index.
*
* @return the disjoint cycles
*/
public Set<Permutation> getDisjointCycles() {
if (disjointCycles == null) {
switch (numberOfCycles) {
case 0 :
disjointCycles = Collections.emptySet();
break;
case 1 :
disjointCycles = Collections.singleton(Permutation.this);
break;
default :
Set<Permutation> set = new HashSet<Permutation>();
int[] array = null;
for (int i = 0; i < cycles.length; i++) {
if (array == null) {
array = new int[correspondence.length];
computeIdentity(array);
}
int a = cycles[i];
if (a < 0) {
a = -1 - a;
array[a] = correspondence[a];
set.add(new Permutation(array, null));
array = null;
} else {
array[a] = correspondence[a];
}
}
disjointCycles = Collections.unmodifiableSet(set);
}
}
return disjointCycles;
}
/**
* The number of times that the permutation would need to be applied
* until it yielded the identity permutation. The orbit of any identity
* permutation is naturally zero.
*
* @return the length of the permutation's orbit
*/
public BigInteger getLengthOfOrbit() {
if (lengthOfOrbit == null) {
if (numberOfCycles == 0) {
lengthOfOrbit = BigInteger.ONE;
} else {
BigInteger[] lengths = new BigInteger[numberOfCycles];
int[] cycles = getCycles();
int count = 0;
int length = 0;
for (int i = 0; i < cycles.length; i++) {
if (cycles[i] < 0) {
lengths[count++] = BigInteger.valueOf(length + 1);
length = 0;
} else {
length++;
}
}
lengthOfOrbit = PermMath.lcm(lengths);
}
}
return lengthOfOrbit;
}
@Override
public int hashCode() {
return Permutation.this.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Info)) return false;
Info that = (Info) obj;
return this.getPermutation().equals(that.getPermutation());
}
@Override
public String toString() {
return "Permutation.Info for " + getPermutation().toString();
}
}
// inner classes
/**
* Provides a set of method for generating permutations that will sort a
* given array or list.
*
* @author Tom Gibara
*/
public static class Sorting {
private static void checkValuesNotNull(Object values) {
if (values == null) throw new IllegalArgumentException("null values");
}
private static Permutation sort(int size, Comparator<Integer> c) {
int[] correspondence = new int[size];
computeIdentity(correspondence);
Stores.ints(correspondence).asList().sort(c);
return new Permutation(correspondence, null);
}
/**
* Creates a permutation that will sort the supplied list. The
* comparator is optional; if it is omitted then the elements of the
* list must be mutually comparable.
*
* @param <E>
* the list element type
* @param values
* the elements to be sorted
* @param c
* an optional comparator which defines the sort order
* @return a permutation which, if applied to the list, would sort it
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> Permutation list(List<E> values, Comparator<? super E> c) {
checkValuesNotNull(values);
return c == null ?
sort(values.size(), (i,j) -> ((Comparable) values.get(i)).compareTo(values.get(j))) :
sort(values.size(), (i,j) -> c.compare(values.get(i), values.get(j)));
}
/**
* Creates a permutation that will sort the supplied array. The
* comparator is optional; if it is omitted then the elements of the
* array must be mutually comparable.
*
* @param <E>
* the array element type
* @param values
* the elements to be sorted
* @param c
* an optional comparator which defines the sort order
* @return a permutation which, if applied to the array, would sort it
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> Permutation objects(E[] values, Comparator<? super E> c) {
checkValuesNotNull(values);
return c == null ?
sort(values.length, (i,j) -> ((Comparable) values[i]).compareTo(values[j])) :
sort(values.length, (i,j) -> c.compare(values[i], values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation bytes(byte... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Byte.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation shorts(short... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Short.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation ints(int... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Integer.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation unsignedInts(int... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Integer.compareUnsigned(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation longs(long... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Long.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation unsignedLongs(long... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Long.compareUnsigned(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation booleans(boolean... values) {
//TODO could optimize this, but is it worth it?
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Boolean.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation chars(char... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Character.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation floats(float... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Float.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation doubles(double... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Double.compare(values[i],values[j]));
}
}
private static abstract class Syncer {
// called to indicate that state of generator has changed
abstract void desync();
// called to invite syncer to update the state of the generator
abstract void resync();
}
/**
* <p>
* Generators provide an efficient way to combine permutations and other
* operations to create new permutations. Most methods on this class return
* the generator itself so that multiple calls can be chained.
*
* <p>
* One way to think of a generator is as a mutable permutation. Another way
* is as a permutation which is itself permutable.
*
* @author Tom Gibara
*
*/
public static final class Generator implements Permutable<Generator> {
final int[] correspondence;
private OrderedSequence orderedSequence = null;
private Syncer syncer;
Generator(int[] correspondence) {
this.correspondence = correspondence;
}
// accessors
/**
* <p>
* Obtains an ordered sequence of all permutations. The permutations are
* ordered consistently with {@link Permutation#compareTo(Permutation)}.
* Thus the first permutation in the sequence is identity and the final
* permutation is reverse.
*
* <p>
* Note that moving through the sequence will change the permutation
* stored by the generator. Correspondingly changing the state of the
* generator will cause the sequence position to alter.
*
* @return an ordered sequence of all permutations.
*/
public PermutationSequence getOrderedSequence() {
return orderedSequence == null ? orderedSequence = new OrderedSequence() : orderedSequence;
}
/**
* <p>
* Obtains a sequence over all involutions with no fixed points. An
* involution in this context is a permutation which is self-inverting.
*
* <p>
* Note that moving through the sequence will change the permutation
* stored by the generator. Correspondingly changing the state of the
* generator will cause the sequence position to alter.
*
* @return a sequence over all permutations that are involutions with
* no fixed points.
*/
public PermutationSequence getFixFreeInvolutionSequence() {
if (syncer instanceof FixFreeInvolutionSequence) return (PermutationSequence) syncer;
if ((correspondence.length & 1) != 0) throw new IllegalStateException("odd order");
return new FixFreeInvolutionSequence();
}
// mutators
/**
* Sets the generated permutation to that specified.
*
* @param permutation
* any permutation
* @return the generator
*/
public Generator set(Permutation permutation) {
if (permutation == null) throw new IllegalArgumentException("null permutation");
if (permutation.size() != correspondence.length) throw new IllegalArgumentException("incorrect size");
permutation.generator(this);
desync();
return this;
}
/**
* Sets the generated permutation to the identity permutation.
*
* @return the generator
*/
public Generator setIdentity() {
computeIdentity(correspondence);
desync();
return this;
}
/**
* Changes generated permutation to the inverse of its current value.
*
* @return the generator
*/
public Generator invert() {
System.arraycopy(computeInverse(correspondence), 0, correspondence, 0, correspondence.length);
desync();
return this;
}
/**
* Raises the generated permutation to the specified power. A zero
* parameter will always yield the identity permutation. Supplying a
* negative power will invert the permutation.
*
* @param power
* a power to which the generaed permutation should be raised
* @return the generator
*/
public Generator power(int power) {
if (power == 0) return setIdentity();
if (power < 0) {
invert();
power = -power;
}
if (power > 1) {
//TODO could be made more efficient
Permutation p = permutation();
setIdentity();
while (power > 0) {
if ((power & 1) == 1) this.apply(p);
p = p.generator().apply(p).permutation();
power >>= 1;
}
}
desync();
return this;
}
// factory methods
/**
* The generated permutation.
*
* @return the generated permutation.
*/
public Permutation permutation() {
resync();
return new Permutation(this);
}
// permutable interface
@Override
public Generator apply(Permutation permutation) {
if (permutation == null) throw new IllegalArgumentException("null permutation");
if (permutation.size() != correspondence.length) throw new IllegalArgumentException("size mismatched");
permutation.permute((i,j) -> swap(i, j));
desync();
return this;
}
@Override
public Generator permuted() {
return this;
}
public int size() {
return correspondence.length;
}
@Override
public Generator reverse() {
int h = correspondence.length / 2;
for (int i = 0, j = correspondence.length - 1; i < h; i++, j--) {
swap(i, j);
}
desync();
return this;
}
@Override
public Generator transpose(int i, int j) {
if (i < 0) throw new IllegalArgumentException("negative i");
if (j < 0) throw new IllegalArgumentException("negative j");
if (i >= correspondence.length) throw new IllegalArgumentException("i greater than or equal to size");
if (j >= correspondence.length) throw new IllegalArgumentException("j greater than or equal to size");
if (i != j) {
int t = correspondence[i];
correspondence[i] = correspondence[j];
correspondence[j] = t;
desync();
}
return this;
}
@Override
public Generator rotate(int distance) {
int size = correspondence.length;
if (size == 0) return this;
distance = distance % size;
if (distance == 0) return this;
if (distance < 0) distance += size;
for (int start = 0, count = 0; count != size; start++) {
int prev = correspondence[start];
int i = start;
do {
i += distance;
if (i >= size) i -= size;
int next = correspondence[i];
correspondence[i] = prev;
prev = next;
count ++;
} while(i != start);
}
desync();
return this;
}
@Override
public Generator cycle(int... cycle) {
if (cycle == null) throw new IllegalArgumentException("null cycle");
int length = cycle.length;
if (length > correspondence.length) throw new IllegalArgumentException("cycle larger than permutation");
switch (length) {
case 0:
// nothing to do
return this;
case 1: {
// just check argument
int i = cycle[0];
if (i < 0) throw new IllegalArgumentException("negative index: " + i);
if (i >= correspondence.length) throw new IllegalArgumentException("index too large: " + i);
return this;
}
case 2: {
int i = cycle[0];
int j = cycle[1];
// check for dupes...
if (i == j) throw new IllegalArgumentException("cycle contains duplicate index: " + i);
// ... otherwise treat as a transposition
return transpose(i, j);
}
default:
// check for dupes in cycle
verifyUnique(correspondence.length, cycle);
// now start cycling
int target = cycle[0];
int t = correspondence[target];
for (int i = 1; i < length; i++) {
int source = cycle[i];
correspondence[target] = correspondence[source];
target = source;
}
correspondence[target] = t;
return this;
}
}
@Override
public Generator shuffle(Random random) {
if (random == null) throw new IllegalArgumentException("null random");
computeShuffle(correspondence, random);
desync();
return this;
}
// object methods
// equality predicated on strict object equality
@Override
public String toString() {
return Arrays.toString(correspondence);
}
// private utility methods
private void desync() {
if (syncer != null) syncer.desync();
}
private void resync() {
if (syncer != null) syncer.resync();
}
private void setSyncer(Syncer syncer) {
if (syncer == this.syncer) return;
if (this.syncer != null) syncer.desync();
this.syncer = syncer;
}
private void swap(int i, int j) {
if (i == j) return;
int t = correspondence[i];
correspondence[i] = correspondence[j];
correspondence[j] = t;
}
private void nextByNumber(boolean ascending) {
int len = correspondence.length;
int j = -1;
for (int i = len - 2; i >= 0; i--) {
if (ascending ? correspondence[i] < correspondence[i + 1] : correspondence[i] > correspondence[i + 1]) {
j = i;
break;
}
}
if (j == -1) throw new IllegalStateException("no such permutation");
int c = correspondence[j];
int k = 0;
for (int i = len - 1; i > j; i--) {
if (ascending ? c < correspondence[i] : c > correspondence[i]) {
k = i;
break;
}
}
swap(j, k);
int h = (j + 1 + len) / 2;
for (int i = j + 1, m = len - 1; i < h; i++, m--) {
swap(i, m);
}
}
private void makeIdentity() {
for (int i = 0; i < correspondence.length; i++) {
correspondence[i] = i;
}
}
private void makeReverse() {
int max = correspondence.length - 1;
for (int i = 0; i <= max; i++) {
correspondence[i] = max - i;
}
}
private void makeSwaps() {
for (int i = 0; i < correspondence.length; i++) {
correspondence[i] = i++ + 1;
correspondence[i] = i - 1;
}
}
private final class OrderedSequence implements PermutationSequence {
public boolean hasNext() {
int[] array = correspondence;
for (int i = 1; i < array.length; i++) {
if (array[i] > array[i - 1]) return true;
}
return false;
}
public boolean hasPrevious() {
int[] array = correspondence;
for (int i = 1; i < array.length; i++) {
if (array[i] < array[i - 1]) return true;
}
return false;
}
@Override
public PermutationSequence first() {
makeIdentity();
return this;
}
@Override
public PermutationSequence last() {
makeReverse();
return this;
}
@Override
public PermutationSequence next() {
nextByNumber(true);
return this;
}
@Override
public PermutationSequence previous() {
nextByNumber(false);
return this;
}
@Override
public Generator getGenerator() {
return Generator.this;
}
@Override
public String toString() {
return "OrderedSequence at " + Generator.this.toString();
}
}
private final class FixFreeInvolutionSequence extends Syncer implements PermutationSequence {
private boolean theyChanged;
private boolean weChanged;
private final int[] values = new int[correspondence.length / 2];
FixFreeInvolutionSequence() {
setSyncer(this);
theyChanged = true;
weChanged = false;
}
@Override
public boolean hasNext() {
if (theyChanged) index();
int limit = values.length * 2 - 2;
for (int i = 0; i < values.length; i++) {
if (values[i] < limit) return true;
limit -= 2;
}
return false;
}
@Override
public boolean hasPrevious() {
if (theyChanged) index();
for (int i = 0; i < values.length; i++) {
if (values[i] > 0) return true;
}
return false;
}
@Override
public PermutationSequence first() {
makeSwaps();
Arrays.fill(values, 0);
sync();
return this;
}
@Override
public PermutationSequence last() {
makeReverse();
int steps = values.length - 1;
for (int i = 0; i <= steps; i++) {
values[i] = 2 * (steps - i);
}
sync();
return this;
}
@Override
public PermutationSequence next() {
if (theyChanged) index();
boolean overflow = true;
int limit = 2;
for (int i = values.length - 2; i >= 0; i--) {
if (values[i] < limit) {
values[i]++;
overflow = false;
break;
}
values[i] = 0;
limit += 2;
}
if (overflow) throw new IllegalStateException("no such permutation");
weChanged = true;
return this;
}
@Override
public PermutationSequence previous() {
if (theyChanged) index();
boolean overflow = true;
int limit = 2;
for (int i = values.length - 2; i >= 0; i--) {
if (values[i] > 0) {
values[i]--;
overflow = false;
break;
}
values[i] = limit;
limit += 2;
}
if (overflow) throw new IllegalStateException("no such permutation");
weChanged = true;
return this;
}
@Override
public Generator getGenerator() {
return Generator.this;
}
@Override
void desync() {
theyChanged = true;
weChanged = false;
}
@Override
void resync() {
if (weChanged) correspond();
}
// clears supplied array, populates values
private void index() {
int[] correspondence = Generator.this.correspondence.clone();
for (int i = 0; i < values.length; i++) {
int j = correspondence[0];
if (j == 0 || correspondence[j] != 0) throw new IllegalStateException("not fix free involution");
values[i] = j - 1;
int length = correspondence.length - 2 * i;
int m = 0;
for (int n = 1; n < correspondence.length; n++) {
if (n != j) {
int c = correspondence[n];
correspondence[m++] = c >= j ? c - 2 : c - 1;
}
}
correspondence[length - 1] = -1;
correspondence[length - 2] = -1;
}
if (syncer == this) {
theyChanged = false;
weChanged = false;
}
}
private void correspond() {
Arrays.fill(correspondence, -1);
int steps = values.length - 1;
for (int a = 0; a <= steps; a++) {
int b = values[a];
int ai = -1;
int bi = -1;
for (int i = 0; i < correspondence.length; i++) {
if (correspondence[i] == -1) {
if (ai >= 0) { // case where a is already placed
if (b == 0) { // case where we need to place "b"
bi = i;
break;
} else { // case where we need to look further to place "b"
b--;
}
} else { // case where we need to place "a"
ai = i;
}
} else { // case where correspondence is already set
/* do nothing */
}
}
correspondence[ai] = bi;
correspondence[bi] = ai;
}
sync();
}
private void sync() {
setSyncer(this);
weChanged = false;
theyChanged = false;
}
@Override
public String toString() {
return "FixFreeInvolutionSequence at " + Generator.this.toString();
}
}
}
} |
Java | public final class Info {
private final static int BIT_GET_REVERSAL = 0;
private final static int BIT_SET_REVERSAL = 1;
private final static int BIT_GET_ROTATION = 2;
private final static int BIT_SET_ROTATION = 3;
private final static int MSK_GET_REVERSAL = 1 << BIT_GET_REVERSAL;
private final static int MSK_SET_REVERSAL = 1 << BIT_SET_REVERSAL;
private final static int MSK_GET_ROTATION = 1 << BIT_GET_ROTATION;
private final static int MSK_SET_ROTATION = 1 << BIT_SET_ROTATION;
// computed eagerly
private final int numberOfCycles;
private final int numberOfTranspositions;
// computed lazily
private short flags = 0;
private BitStore fixedPoints;
private Set<Permutation> disjointCycles;
private BigInteger lengthOfOrbit;
Info() {
// ensure number of cycles has been computed
// set properties that are cheap, eagerly
int numberOfCycles = 0;
int[] cycles = getCycles();
for (int i = 0; i < cycles.length; i++) {
if (cycles[i] < 0) numberOfCycles++;
}
this.numberOfCycles = numberOfCycles;
numberOfTranspositions = cycles.length - numberOfCycles;
}
/**
* The permutation about which information is being provided.
*
* @return the permutation
*/
public Permutation getPermutation() {
return Permutation.this;
}
/**
* The number of disjoint cycles. All permutations can be decomposed
* into a set of disjoint cycles.
*
* @return the number of cycles
* @see #getDisjointCycles()
*/
public int getNumberOfCycles() {
return numberOfCycles;
}
/**
* The number of transpositions made by the permutation. All
* permutations are applied as a sequence of transpositions.
*
* @return the number of transpositions
*/
public int getNumberOfTranspositions() {
return numberOfTranspositions;
}
/**
* Whether the permutation makes no changes to the indexing of values.
*
* @return whether the permutation is the identity permutation
*/
public boolean isIdentity() {
return numberOfTranspositions == 0;
}
/**
* Whether the permutation consists of an odd number of transpositions.
*
* @return whether the permutation is odd
*/
public boolean isOdd() {
return (numberOfTranspositions & 1) == 1;
}
/**
* Whether the permutation consists of a single transposition.
*
* @return whether the permutation is a transposition
* @see Permutation#transpose(int, int, int)
*/
public boolean isTransposition() {
return numberOfTranspositions == 1;
}
/**
* Whether the permutation reverses the indexing of values.
*
* @return whether the permutation is a reversal
* @see Permutation#reverse(int)
*/
public boolean isReversal() {
int m = MSK_SET_REVERSAL | MSK_GET_REVERSAL;
int bits = flags & m;
if (bits != 0) return bits == m;
boolean f = isReversalImpl();
flags |= f ? m : MSK_SET_REVERSAL;
return f;
}
private boolean isReversalImpl() {
int len = correspondence.length - 1;
for (int i = 0; i <= len; i++) {
if (correspondence[i] != len - i) return false;
}
return true;
}
/**
* Whether the permutation consists of a single cycle.
*
* @return whether the permutation is cyclic.
* @see Permutation#cycle(int, int...)
*/
public boolean isCyclic() {
return numberOfCycles == 1;
}
/**
* Whether the permutation is a rotation.
*
* @return whether the permutation is a rotation
* @see Permutation#rotate(int, int)
*/
public boolean isRotation() {
int m = MSK_SET_ROTATION | MSK_GET_ROTATION;
int bits = flags & m;
if (bits != 0) return bits == m;
boolean f = isRotationImpl();
flags |= f ? m : MSK_SET_ROTATION;
return f;
}
private boolean isRotationImpl() {
int length = correspondence.length;
if (length < 3) return true;
if (isIdentity()) return true;
int e = correspondence[0];
for (int i = 0; i < length; i++) {
if (correspondence[i] != e) return false;
e++;
if (e == length) e -= length;
}
return true;
}
/**
* Optionally, the distance through which the permutation rotates
* values. The rotation distance of any identity permutation is zero.
*
* @return the distance of rotation, or empty if the permutation is not
* a rotation
* @see Permutation#rotate(int, int)
*/
public Optional<Integer> rotationDistance() {
if (isIdentity()) return Optional.of(0);
if (isRotation()) return Optional.of(correspondence.length - correspondence[0]);
return Optional.empty();
}
/**
* <p>
* An immutable bit store indicating the positions at which values
* remain untouched by the permutation. That is:
* <code>p.info().getFixedPoints().getBit(i)</code> is true iff
* <code>p.correspondence()[i] == i</code>
*
* <p>
* Note that the supplied bits can be viewed as a set of integer
* positions using: <code>p.info().getFixedPoints().asSet()</code>
*
* @return bits the positions that are fixed by the permutation.
*/
public BitStore getFixedPoints() {
if (fixedPoints == null) {
int[] array = correspondence;
fixedPoints = Bits.store(array.length);
for (int i = 0; i < array.length; i++) {
if (array[i] == i) fixedPoints.setBit(i, true);
}
fixedPoints = fixedPoints.immutableCopy();
}
return fixedPoints;
}
/**
* The disjoint cycles of the permutation. Each permutation in the
* returned set is cyclic and no two permutations will transpose values
* at the same index.
*
* @return the disjoint cycles
*/
public Set<Permutation> getDisjointCycles() {
if (disjointCycles == null) {
switch (numberOfCycles) {
case 0 :
disjointCycles = Collections.emptySet();
break;
case 1 :
disjointCycles = Collections.singleton(Permutation.this);
break;
default :
Set<Permutation> set = new HashSet<Permutation>();
int[] array = null;
for (int i = 0; i < cycles.length; i++) {
if (array == null) {
array = new int[correspondence.length];
computeIdentity(array);
}
int a = cycles[i];
if (a < 0) {
a = -1 - a;
array[a] = correspondence[a];
set.add(new Permutation(array, null));
array = null;
} else {
array[a] = correspondence[a];
}
}
disjointCycles = Collections.unmodifiableSet(set);
}
}
return disjointCycles;
}
/**
* The number of times that the permutation would need to be applied
* until it yielded the identity permutation. The orbit of any identity
* permutation is naturally zero.
*
* @return the length of the permutation's orbit
*/
public BigInteger getLengthOfOrbit() {
if (lengthOfOrbit == null) {
if (numberOfCycles == 0) {
lengthOfOrbit = BigInteger.ONE;
} else {
BigInteger[] lengths = new BigInteger[numberOfCycles];
int[] cycles = getCycles();
int count = 0;
int length = 0;
for (int i = 0; i < cycles.length; i++) {
if (cycles[i] < 0) {
lengths[count++] = BigInteger.valueOf(length + 1);
length = 0;
} else {
length++;
}
}
lengthOfOrbit = PermMath.lcm(lengths);
}
}
return lengthOfOrbit;
}
@Override
public int hashCode() {
return Permutation.this.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Info)) return false;
Info that = (Info) obj;
return this.getPermutation().equals(that.getPermutation());
}
@Override
public String toString() {
return "Permutation.Info for " + getPermutation().toString();
}
} |
Java | public static class Sorting {
private static void checkValuesNotNull(Object values) {
if (values == null) throw new IllegalArgumentException("null values");
}
private static Permutation sort(int size, Comparator<Integer> c) {
int[] correspondence = new int[size];
computeIdentity(correspondence);
Stores.ints(correspondence).asList().sort(c);
return new Permutation(correspondence, null);
}
/**
* Creates a permutation that will sort the supplied list. The
* comparator is optional; if it is omitted then the elements of the
* list must be mutually comparable.
*
* @param <E>
* the list element type
* @param values
* the elements to be sorted
* @param c
* an optional comparator which defines the sort order
* @return a permutation which, if applied to the list, would sort it
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> Permutation list(List<E> values, Comparator<? super E> c) {
checkValuesNotNull(values);
return c == null ?
sort(values.size(), (i,j) -> ((Comparable) values.get(i)).compareTo(values.get(j))) :
sort(values.size(), (i,j) -> c.compare(values.get(i), values.get(j)));
}
/**
* Creates a permutation that will sort the supplied array. The
* comparator is optional; if it is omitted then the elements of the
* array must be mutually comparable.
*
* @param <E>
* the array element type
* @param values
* the elements to be sorted
* @param c
* an optional comparator which defines the sort order
* @return a permutation which, if applied to the array, would sort it
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> Permutation objects(E[] values, Comparator<? super E> c) {
checkValuesNotNull(values);
return c == null ?
sort(values.length, (i,j) -> ((Comparable) values[i]).compareTo(values[j])) :
sort(values.length, (i,j) -> c.compare(values[i], values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation bytes(byte... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Byte.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation shorts(short... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Short.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation ints(int... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Integer.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation unsignedInts(int... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Integer.compareUnsigned(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation longs(long... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Long.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation unsignedLongs(long... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Long.compareUnsigned(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation booleans(boolean... values) {
//TODO could optimize this, but is it worth it?
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Boolean.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation chars(char... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Character.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation floats(float... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Float.compare(values[i],values[j]));
}
/**
* Creates a permutation that will sort the supplied array.
*
* @param values
* the elements to be sorted
* @return a permutation which, if applied to the array, would sort it
*/
public static Permutation doubles(double... values) {
checkValuesNotNull(values);
return sort(values.length, (i,j) -> Double.compare(values[i],values[j]));
}
} |
Java | public static final class Generator implements Permutable<Generator> {
final int[] correspondence;
private OrderedSequence orderedSequence = null;
private Syncer syncer;
Generator(int[] correspondence) {
this.correspondence = correspondence;
}
// accessors
/**
* <p>
* Obtains an ordered sequence of all permutations. The permutations are
* ordered consistently with {@link Permutation#compareTo(Permutation)}.
* Thus the first permutation in the sequence is identity and the final
* permutation is reverse.
*
* <p>
* Note that moving through the sequence will change the permutation
* stored by the generator. Correspondingly changing the state of the
* generator will cause the sequence position to alter.
*
* @return an ordered sequence of all permutations.
*/
public PermutationSequence getOrderedSequence() {
return orderedSequence == null ? orderedSequence = new OrderedSequence() : orderedSequence;
}
/**
* <p>
* Obtains a sequence over all involutions with no fixed points. An
* involution in this context is a permutation which is self-inverting.
*
* <p>
* Note that moving through the sequence will change the permutation
* stored by the generator. Correspondingly changing the state of the
* generator will cause the sequence position to alter.
*
* @return a sequence over all permutations that are involutions with
* no fixed points.
*/
public PermutationSequence getFixFreeInvolutionSequence() {
if (syncer instanceof FixFreeInvolutionSequence) return (PermutationSequence) syncer;
if ((correspondence.length & 1) != 0) throw new IllegalStateException("odd order");
return new FixFreeInvolutionSequence();
}
// mutators
/**
* Sets the generated permutation to that specified.
*
* @param permutation
* any permutation
* @return the generator
*/
public Generator set(Permutation permutation) {
if (permutation == null) throw new IllegalArgumentException("null permutation");
if (permutation.size() != correspondence.length) throw new IllegalArgumentException("incorrect size");
permutation.generator(this);
desync();
return this;
}
/**
* Sets the generated permutation to the identity permutation.
*
* @return the generator
*/
public Generator setIdentity() {
computeIdentity(correspondence);
desync();
return this;
}
/**
* Changes generated permutation to the inverse of its current value.
*
* @return the generator
*/
public Generator invert() {
System.arraycopy(computeInverse(correspondence), 0, correspondence, 0, correspondence.length);
desync();
return this;
}
/**
* Raises the generated permutation to the specified power. A zero
* parameter will always yield the identity permutation. Supplying a
* negative power will invert the permutation.
*
* @param power
* a power to which the generaed permutation should be raised
* @return the generator
*/
public Generator power(int power) {
if (power == 0) return setIdentity();
if (power < 0) {
invert();
power = -power;
}
if (power > 1) {
//TODO could be made more efficient
Permutation p = permutation();
setIdentity();
while (power > 0) {
if ((power & 1) == 1) this.apply(p);
p = p.generator().apply(p).permutation();
power >>= 1;
}
}
desync();
return this;
}
// factory methods
/**
* The generated permutation.
*
* @return the generated permutation.
*/
public Permutation permutation() {
resync();
return new Permutation(this);
}
// permutable interface
@Override
public Generator apply(Permutation permutation) {
if (permutation == null) throw new IllegalArgumentException("null permutation");
if (permutation.size() != correspondence.length) throw new IllegalArgumentException("size mismatched");
permutation.permute((i,j) -> swap(i, j));
desync();
return this;
}
@Override
public Generator permuted() {
return this;
}
public int size() {
return correspondence.length;
}
@Override
public Generator reverse() {
int h = correspondence.length / 2;
for (int i = 0, j = correspondence.length - 1; i < h; i++, j--) {
swap(i, j);
}
desync();
return this;
}
@Override
public Generator transpose(int i, int j) {
if (i < 0) throw new IllegalArgumentException("negative i");
if (j < 0) throw new IllegalArgumentException("negative j");
if (i >= correspondence.length) throw new IllegalArgumentException("i greater than or equal to size");
if (j >= correspondence.length) throw new IllegalArgumentException("j greater than or equal to size");
if (i != j) {
int t = correspondence[i];
correspondence[i] = correspondence[j];
correspondence[j] = t;
desync();
}
return this;
}
@Override
public Generator rotate(int distance) {
int size = correspondence.length;
if (size == 0) return this;
distance = distance % size;
if (distance == 0) return this;
if (distance < 0) distance += size;
for (int start = 0, count = 0; count != size; start++) {
int prev = correspondence[start];
int i = start;
do {
i += distance;
if (i >= size) i -= size;
int next = correspondence[i];
correspondence[i] = prev;
prev = next;
count ++;
} while(i != start);
}
desync();
return this;
}
@Override
public Generator cycle(int... cycle) {
if (cycle == null) throw new IllegalArgumentException("null cycle");
int length = cycle.length;
if (length > correspondence.length) throw new IllegalArgumentException("cycle larger than permutation");
switch (length) {
case 0:
// nothing to do
return this;
case 1: {
// just check argument
int i = cycle[0];
if (i < 0) throw new IllegalArgumentException("negative index: " + i);
if (i >= correspondence.length) throw new IllegalArgumentException("index too large: " + i);
return this;
}
case 2: {
int i = cycle[0];
int j = cycle[1];
// check for dupes...
if (i == j) throw new IllegalArgumentException("cycle contains duplicate index: " + i);
// ... otherwise treat as a transposition
return transpose(i, j);
}
default:
// check for dupes in cycle
verifyUnique(correspondence.length, cycle);
// now start cycling
int target = cycle[0];
int t = correspondence[target];
for (int i = 1; i < length; i++) {
int source = cycle[i];
correspondence[target] = correspondence[source];
target = source;
}
correspondence[target] = t;
return this;
}
}
@Override
public Generator shuffle(Random random) {
if (random == null) throw new IllegalArgumentException("null random");
computeShuffle(correspondence, random);
desync();
return this;
}
// object methods
// equality predicated on strict object equality
@Override
public String toString() {
return Arrays.toString(correspondence);
}
// private utility methods
private void desync() {
if (syncer != null) syncer.desync();
}
private void resync() {
if (syncer != null) syncer.resync();
}
private void setSyncer(Syncer syncer) {
if (syncer == this.syncer) return;
if (this.syncer != null) syncer.desync();
this.syncer = syncer;
}
private void swap(int i, int j) {
if (i == j) return;
int t = correspondence[i];
correspondence[i] = correspondence[j];
correspondence[j] = t;
}
private void nextByNumber(boolean ascending) {
int len = correspondence.length;
int j = -1;
for (int i = len - 2; i >= 0; i--) {
if (ascending ? correspondence[i] < correspondence[i + 1] : correspondence[i] > correspondence[i + 1]) {
j = i;
break;
}
}
if (j == -1) throw new IllegalStateException("no such permutation");
int c = correspondence[j];
int k = 0;
for (int i = len - 1; i > j; i--) {
if (ascending ? c < correspondence[i] : c > correspondence[i]) {
k = i;
break;
}
}
swap(j, k);
int h = (j + 1 + len) / 2;
for (int i = j + 1, m = len - 1; i < h; i++, m--) {
swap(i, m);
}
}
private void makeIdentity() {
for (int i = 0; i < correspondence.length; i++) {
correspondence[i] = i;
}
}
private void makeReverse() {
int max = correspondence.length - 1;
for (int i = 0; i <= max; i++) {
correspondence[i] = max - i;
}
}
private void makeSwaps() {
for (int i = 0; i < correspondence.length; i++) {
correspondence[i] = i++ + 1;
correspondence[i] = i - 1;
}
}
private final class OrderedSequence implements PermutationSequence {
public boolean hasNext() {
int[] array = correspondence;
for (int i = 1; i < array.length; i++) {
if (array[i] > array[i - 1]) return true;
}
return false;
}
public boolean hasPrevious() {
int[] array = correspondence;
for (int i = 1; i < array.length; i++) {
if (array[i] < array[i - 1]) return true;
}
return false;
}
@Override
public PermutationSequence first() {
makeIdentity();
return this;
}
@Override
public PermutationSequence last() {
makeReverse();
return this;
}
@Override
public PermutationSequence next() {
nextByNumber(true);
return this;
}
@Override
public PermutationSequence previous() {
nextByNumber(false);
return this;
}
@Override
public Generator getGenerator() {
return Generator.this;
}
@Override
public String toString() {
return "OrderedSequence at " + Generator.this.toString();
}
}
private final class FixFreeInvolutionSequence extends Syncer implements PermutationSequence {
private boolean theyChanged;
private boolean weChanged;
private final int[] values = new int[correspondence.length / 2];
FixFreeInvolutionSequence() {
setSyncer(this);
theyChanged = true;
weChanged = false;
}
@Override
public boolean hasNext() {
if (theyChanged) index();
int limit = values.length * 2 - 2;
for (int i = 0; i < values.length; i++) {
if (values[i] < limit) return true;
limit -= 2;
}
return false;
}
@Override
public boolean hasPrevious() {
if (theyChanged) index();
for (int i = 0; i < values.length; i++) {
if (values[i] > 0) return true;
}
return false;
}
@Override
public PermutationSequence first() {
makeSwaps();
Arrays.fill(values, 0);
sync();
return this;
}
@Override
public PermutationSequence last() {
makeReverse();
int steps = values.length - 1;
for (int i = 0; i <= steps; i++) {
values[i] = 2 * (steps - i);
}
sync();
return this;
}
@Override
public PermutationSequence next() {
if (theyChanged) index();
boolean overflow = true;
int limit = 2;
for (int i = values.length - 2; i >= 0; i--) {
if (values[i] < limit) {
values[i]++;
overflow = false;
break;
}
values[i] = 0;
limit += 2;
}
if (overflow) throw new IllegalStateException("no such permutation");
weChanged = true;
return this;
}
@Override
public PermutationSequence previous() {
if (theyChanged) index();
boolean overflow = true;
int limit = 2;
for (int i = values.length - 2; i >= 0; i--) {
if (values[i] > 0) {
values[i]--;
overflow = false;
break;
}
values[i] = limit;
limit += 2;
}
if (overflow) throw new IllegalStateException("no such permutation");
weChanged = true;
return this;
}
@Override
public Generator getGenerator() {
return Generator.this;
}
@Override
void desync() {
theyChanged = true;
weChanged = false;
}
@Override
void resync() {
if (weChanged) correspond();
}
// clears supplied array, populates values
private void index() {
int[] correspondence = Generator.this.correspondence.clone();
for (int i = 0; i < values.length; i++) {
int j = correspondence[0];
if (j == 0 || correspondence[j] != 0) throw new IllegalStateException("not fix free involution");
values[i] = j - 1;
int length = correspondence.length - 2 * i;
int m = 0;
for (int n = 1; n < correspondence.length; n++) {
if (n != j) {
int c = correspondence[n];
correspondence[m++] = c >= j ? c - 2 : c - 1;
}
}
correspondence[length - 1] = -1;
correspondence[length - 2] = -1;
}
if (syncer == this) {
theyChanged = false;
weChanged = false;
}
}
private void correspond() {
Arrays.fill(correspondence, -1);
int steps = values.length - 1;
for (int a = 0; a <= steps; a++) {
int b = values[a];
int ai = -1;
int bi = -1;
for (int i = 0; i < correspondence.length; i++) {
if (correspondence[i] == -1) {
if (ai >= 0) { // case where a is already placed
if (b == 0) { // case where we need to place "b"
bi = i;
break;
} else { // case where we need to look further to place "b"
b--;
}
} else { // case where we need to place "a"
ai = i;
}
} else { // case where correspondence is already set
/* do nothing */
}
}
correspondence[ai] = bi;
correspondence[bi] = ai;
}
sync();
}
private void sync() {
setSyncer(this);
weChanged = false;
theyChanged = false;
}
@Override
public String toString() {
return "FixFreeInvolutionSequence at " + Generator.this.toString();
}
}
} |
Java | public class PlayerData implements Listener, MauModule {
private Maussentials plugin;
/** Table Names */
public static final String TABLE_PLAYERS = "Players", TABLE_HISTORY = "OldNames", TABLE_IPLOGS = "IPLogs";
/** Used in many tables */
public static final String COLUMN_UUID = "UUID", COLUMN_USERNAME = "Username";
/** Used in IPs table */
public static final String COLUMN_IP = "IP", COLUMN_LASTUSED = "LastUsed";
/** Used in Players table */
public static final String COLUMN_LASTLOGIN = "LastLogin", COLUMN_LOCATION = "Location";
/** Used in OldNames table */
public static final String COLUMN_CHANGEDTO = "ChangedTo";
private boolean loaded = false;
@Override
public void load(Maussentials plugin) {
this.plugin = plugin;
plugin.getServer().getPluginManager().registerEvents(new PDListeners(plugin, this), plugin);
try {
// @mauformat=off
// Create the table Players
plugin.getDB().query("CREATE TABLE " + TABLE_PLAYERS + " ("
+ COLUMN_UUID + " varchar(25) NOT NULL,"
+ COLUMN_USERNAME + " varchar(16) NOT NULL,"
+ COLUMN_LASTLOGIN + " INTEGER NOT NULL,"
+ COLUMN_LOCATION + " TEXT NOT NULL,"
+ "PRIMARY KEY (" + COLUMN_UUID + "));");
// Create the table OldNames
plugin.getDB().query("CREATE TABLE " + TABLE_HISTORY + " ("
+ COLUMN_UUID + " varchar(25) NOT NULL,"
+ COLUMN_USERNAME + " varchar(16) NOT NULL,"
+ COLUMN_CHANGEDTO + " INTEGER NOT NULL,"
+ "PRIMARY KEY (" + COLUMN_UUID + ", " + COLUMN_USERNAME + "));");
// Create the table IPs
plugin.getDB().query("CREATE TABLE " + TABLE_IPLOGS + " ("
+ COLUMN_UUID + " varchar(25) NOT NULL,"
+ COLUMN_IP + " varchar(16) NOT NULL,"
+ COLUMN_LASTUSED + " INTEGER NOT NULL,"
+ "PRIMARY KEY (" + COLUMN_UUID + ", " + COLUMN_IP + "));");
// @mauformat=on
} catch (SQLException e) {}
loaded = true;
}
@Override
public void unload() {
HandlerList.unregisterAll(this);
plugin = null;
loaded = false;
}
@Override
public boolean isLoaded() {
return loaded;
}
/**
* Method to update name history for the specific UUID from Mojang's servers. Called when the
* database system notices that an UUID logs in with an unidentified username.
*/
public void updateNameHistory(UUID uuid) {
try {
// Request the name history of the UUID.
BufferedReader br = new BufferedReader(
new InputStreamReader(new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names").openStream()));
String in = "";
String s;
// Read the response
while ((s = br.readLine()) != null)
in += s;
// Make sure that it isn't empty.
if (in.isEmpty()) throw new RuntimeException("Failed to process name change: Mojang API returned empty name history.");
// Parse the response json.
JsonArray ja = new JsonParser().parse(in).getAsJsonArray();
// Loop through the name change entries and add the details to the string list.
for (int i = 0; i < ja.size(); i++) {
JsonObject jo = ja.get(i).getAsJsonObject();
String name = jo.get("name").getAsString();
try {
// @mauformat=off
ResultSet rs = plugin.getDB().query(
"SELECT * FROM " + TABLE_HISTORY + " WHERE " + COLUMN_UUID + " = '" + uuid.toString() + "'" + " AND " + COLUMN_USERNAME + " = '"
+ name + "'" + ";");
// @mauformat=on
if (!rs.next()) {
if (jo.has("changedToAt")) {
long time = jo.get("changedToAt").getAsLong();
setHistory(uuid, name, time);
} else setHistory(uuid, name, 0);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
throw new RuntimeException("Failed to fetch name history from Mojang API", e1);
}
}
/*
* Methods for updating the values of the database.
*/
// @mauformat=off
public ResultSet setEntry(UUID uuid, String username, SerializableLocation l) throws SQLException {
return plugin.getDB().query(
"REPLACE INTO " + TABLE_PLAYERS + " VALUES (" + "'" + uuid.toString() + "','" + username + "','" + System.currentTimeMillis() + "','"
+ l.toString() + "');");
}
public ResultSet setTime(UUID uuid) throws SQLException {
return plugin.getDB().query(
"UPDATE " + TABLE_PLAYERS + " SET " + COLUMN_LASTLOGIN + "='" + System.currentTimeMillis() + "'" + " WHERE " + COLUMN_UUID + "='"
+ uuid.toString() + "';");
}
public ResultSet setLocation(UUID uuid, SerializableLocation l) throws SQLException {
return plugin.getDB().query(
"UPDATE " + TABLE_PLAYERS + " SET " + COLUMN_LOCATION + "='" + l.toString() + "'" + " WHERE " + COLUMN_UUID + "='" + uuid.toString() + "';");
}
public ResultSet setHistory(UUID uuid, String username, long changedTo) throws SQLException {
return plugin.getDB().query("REPLACE INTO " + TABLE_HISTORY + " VALUES ('" + uuid.toString() + "','" + username + "','" + changedTo + "');");
}
public ResultSet setIPs(UUID uuid, String ip) throws SQLException {
return plugin.getDB().query(
"REPLACE INTO " + TABLE_IPLOGS + " VALUES ('" + uuid.toString() + "','" + ip + "','" + System.currentTimeMillis() + "');");
}
// @mauformat=on
/*
* Getting data from the IP Log
*/
/**
* Get all the UUIDs that have visited from the given IP.
*
* @param ip The IP to search.
* @return A map containing the UUIDs as keys and last used timestamps as values.
* @throws SQLException If database querying or resultset getting throws something.
*/
public Map<UUID, Long> getUUIDsFromIP(String ip) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT * FROM " + TABLE_IPLOGS + " WHERE " + COLUMN_IP + "='" + ip + "';");
Map<UUID, Long> rtrn = new HashMap<UUID, Long>();
while (rs.next())
rtrn.put(UUID.fromString(rs.getString(COLUMN_UUID)), rs.getLong(COLUMN_LASTUSED));
return rtrn;
}
/**
* Get all the IPs that the given UUID has logged in using.
*
* @param uuid The UUID to search.
* @return A map containing the IPs as keys and last used timestamps as values.
* @throws SQLException If database querying or resultset getting throws something.
*/
public Map<String, Long> getIPsFromUUID(UUID uuid) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT * FROM " + TABLE_IPLOGS + " WHERE " + COLUMN_UUID + "='" + uuid.toString() + "';");
Map<String, Long> rtrn = new HashMap<String, Long>();
while (rs.next())
rtrn.put(rs.getString(COLUMN_IP), rs.getLong(COLUMN_LASTUSED));
return rtrn;
}
/**
* Get the latest IP of the given UUID. The IP may be currently being used (if the player is
* logged in currently). The IP may also be null, if the given UUID has never logged in.
*
* @param uuid The UUID to search.
* @return The latest known IP of the UUID, or null if the UUID has never logged in.
* @throws SQLException If database querying or resultset getting throws something.
*/
public String getLatestIPByUUID(UUID uuid) throws SQLException {
// Check if the given player is online. If online, return the IP directly from the player
// instance without any
// SQL queries.
Player p = Bukkit.getServer().getPlayer(uuid);
if (p != null) return p.getAddress().getAddress().getHostAddress();
// The player is not online, use the IP log table.
Map<String, Long> ips = getIPsFromUUID(uuid);
Entry<String, Long> latest = null;
// Loop through the query result IPs and find the one with the biggest used at timestamp.
for (Entry<String, Long> ip : ips.entrySet())
if (latest == null || latest.getValue() < ip.getValue()) latest = ip;
// Return the IP from the IP log table, or null if there weren't any entries.
return latest != null ? latest.getKey() : null;
}
/*
* Getting data from the Name History table
*/
/**
* Get all the usernames that the given UUID has logged in using.
*
* @param uuid The UUID to search.
* @return A map containing the usernames as keys and changed to timestamps as values.
* @throws SQLException If database querying or resultset getting throws something.
*/
public Map<String, Long> getNamesFromUUID(UUID uuid) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT * FROM " + TABLE_HISTORY + " WHERE " + COLUMN_UUID + "='" + uuid.toString() + "';");
Map<String, Long> rtrn = new HashMap<String, Long>();
while (rs.next())
rtrn.put(rs.getString(COLUMN_USERNAME), rs.getLong(COLUMN_CHANGEDTO));
return rtrn;
}
/**
* Get all the UUIDs that the given username has been used by.
*
* @param username The username to search.
* @return A map containing the UUIDs as keys and changed to timestamps as values.
* @throws SQLException If database querying or resultset getting throws something.
*/
public Map<UUID, Long> getUUIDsFromName(String username) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT * FROM " + TABLE_HISTORY + " WHERE " + COLUMN_USERNAME + "='" + username + "';");
Map<UUID, Long> rtrn = new HashMap<UUID, Long>();
while (rs.next())
rtrn.put(UUID.fromString(rs.getString(COLUMN_UUID)), rs.getLong(COLUMN_CHANGEDTO));
return rtrn;
}
/**
* Get the latest UUID who has owned the given name. The name may still be in use by the
* returned UUID. If a player with the given name is online, the UUID will be fetched directly
* from the player instance.. The UUID will be null if the name could not be found in the
* database.
*
* @param username The username to search.
* @return The UUID who has previously used or is using the given name, or null if the nobody
* has ever logged in using the given name.
* @throws SQLException If database querying or resultset getting throws something.
*/
public UUID getLatestUUIDByName(String username) throws SQLException {
// Check if a player is online by the given name. If online, return the UUID directly from
// the player without
// any SQL queries.
Player p = Bukkit.getPlayer(username);
if (p != null) return p.getUniqueId();
// The username is not online, check the Players table for an UUID.
UUID u = getUUIDByName(username);
if (u != null) return u;
// The players table does not contain any entries with the given name. Use the name history
// table.
Map<UUID, Long> uuids = getUUIDsFromName(username);
// Loop through the query result UUIDs and find the one with the biggest changedTo
// timestamp.
Entry<UUID, Long> latest = null;
for (Entry<UUID, Long> uuid : uuids.entrySet())
if (latest == null || latest.getValue() < uuid.getValue()) latest = uuid;
// Return the UUID from the history table, or null if there weren't any entries.
return latest != null ? latest.getKey() : null;
}
/*
* Getting data from the Players table.
*/
/**
* Get the latest logged username of the given UUID.
*
* @param u The UUID to get the username from.
* @return The username.
* @throws SQLException If database querying or resultset getting throws something.
*/
public String getNameByUUID(UUID u) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_PLAYERS + " WHERE " + COLUMN_UUID + "='" + u.toString() + "';");
if (rs.next()) return rs.getString(COLUMN_USERNAME);
else return null;
}
/**
* Get the UUID which has used the given username previously.
*
* @param name The username to get the UUID from
* @return The UUID.
* @throws SQLException As defined in {@link Database#query(String)}, {@link ResultSet#next()}
* and {@link ResultSet#getString(String)}
*/
public UUID getUUIDByName(String name) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT " + COLUMN_UUID + " FROM " + TABLE_PLAYERS + " WHERE " + COLUMN_USERNAME + "='" + name + "';");
if (rs.next()) return UUID.fromString(rs.getString(COLUMN_UUID));
else return null;
}
/**
* Get the last time the given UUID logged in.
*
* @param u The UUID to search.
* @return The timestamp, or -1 if the player has never logged in.
* @throws SQLException As defined in {@link Database#query(String)}, {@link ResultSet#next()}
* and {@link ResultSet#getLong(String)}
*/
public long getLastLoginByUUID(UUID u) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT " + COLUMN_LASTLOGIN + " FROM " + TABLE_PLAYERS + " WHERE " + COLUMN_UUID + "='" + u.toString() + "';");
if (rs.next()) return rs.getLong(COLUMN_LASTLOGIN);
else return -1;
}
/**
* Get the logout/login location of the given UUID.
*
* @param u The UUID to search.
* @return The location, or null if none found.
* @throws SQLException As defined in {@link Database#query(String)}, {@link ResultSet#next()}
* and {@link ResultSet#getString(String)}
*/
public SerializableLocation getLocationByUUID(UUID u) throws SQLException {
ResultSet rs = plugin.getDB().query("SELECT " + COLUMN_LOCATION + " FROM " + TABLE_PLAYERS + " WHERE " + COLUMN_UUID + "='" + u.toString() + "';");
if (rs.next()) return SerializableLocation.fromString(rs.getString(COLUMN_LOCATION));
else return null;
}
@Override
public String[] getDependencies() {
return new String[] { "database" };
}
} |
Java | public class ImageListFragment extends Fragment implements AdapterView.OnItemClickListener {
public static final int THUMBNAIL_IMAGE_WIDTH = 50;
public StickyListHeadersListView mStickyList;
private ImageListAdapter mAdapter;
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
public ImageListFragment() {
} //empty ctor as per Fragment docs
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_list_fragment, container, false);
mStickyList = (StickyListHeadersListView) view.findViewById(R.id.image_list_view);
mStickyList.setOnItemClickListener(this);
mAdapter = new ImageListAdapter(this.getActivity());
mStickyList.setAdapter(mAdapter);
mStickyList.setDrawingListUnderStickyHeader(false);
IntentFilter filter = new IntentFilter(EvernoteMars.END_NOTE_LOADING);
filter.addAction(MarsImagesApp.MISSION_CHANGED);
filter.addAction(MarsImagesApp.IMAGE_SELECTED);
filter.addAction(MarsImagesApp.NOTES_CLEARED);
filter.addAction(MarsImagesApp.LOCATIONS_LOADED);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, filter);
return view;
}
private final BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MarsImagesApp.MISSION_CHANGED) ||
intent.getAction().equals(MarsImagesApp.NOTES_CLEARED)) {
mAdapter.setCount(0);
mAdapter.notifyDataSetChanged();
} else if (intent.getAction().equals(EvernoteMars.END_NOTE_LOADING)) {
mAdapter.setCount(EVERNOTE.getNotesCount());
mAdapter.notifyDataSetChanged();
} else if (intent.getAction().equals(MarsImagesApp.IMAGE_SELECTED)) {
String selectionSource = intent.getStringExtra(MarsImagesApp.SELECTION_SOURCE);
if (!selectionSource.equals(MarsImagesApp.LIST_SOURCE)) {
int i = intent.getIntExtra(MarsImagesApp.IMAGE_INDEX, 0);
mAdapter.setSelectedPosition(i);
scrollToShowItem(i);
}
} else if (intent.getAction().equals(MarsImagesApp.LOCATIONS_LOADED)) {
ImageListActivity activity = (ImageListActivity) getActivity();
MarsImagesApp.enableMenuItem(activity.mMosaicMenuItem);
// MarsImagesApp.enableMenuItem(activity.mMapMenuItem);
}
}
};
private void scrollToShowItem(int position) {
int firstVisiblePosition = mStickyList.getFirstVisiblePosition();
int lastVisiblePosition = mStickyList.getLastVisiblePosition();
if (position < firstVisiblePosition || position > lastVisiblePosition) {
mStickyList.smoothScrollToPosition(position);
}
}
@Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMessageReceiver);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long id) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mAdapter.setSelectedPosition(i);
mCallbacks.onItemSelected(i);
}
private class ImageListAdapter extends BaseAdapter implements StickyListHeadersAdapter {
private final LayoutInflater inflater;
private int mItemCount;
private int selectedPosition = 0;
public ImageListAdapter(Context context) {
inflater = LayoutInflater.from(context);
mItemCount = EVERNOTE.getNotesCount();
}
public void setSelectedPosition(int selectedPosition) {
this.selectedPosition = selectedPosition;
notifyDataSetChanged();
}
@Override
public View getHeaderView(int i, View view, ViewGroup viewGroup) {
HeaderViewHolder holder;
if (view == null) {
holder = new HeaderViewHolder();
view = inflater.inflate(R.layout.list_header, viewGroup, false);
holder.text = (TextView) view.findViewById(R.id.header_title);
view.setTag(holder);
} else {
holder = (HeaderViewHolder) view.getTag();
}
//set header text as first char in name
String headerText = MARS_IMAGES.getMission().getSectionText(EVERNOTE.getNote(i));
holder.text.setText(headerText);
return view;
}
@Override
public long getHeaderId(int i) {
return MARS_IMAGES.getMission().getSol(EVERNOTE.getNote(i));
}
@Override
public int getCount() {
return mItemCount;
}
@Override
public Object getItem(int i) {
return EVERNOTE.getNote(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View recycledView, ViewGroup viewGroup) {
ViewHolder holder;
View view;
if (recycledView == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.row, viewGroup, false);
holder.row = view.findViewById(R.id.list_row);
holder.text = (TextView) view.findViewById(R.id.row_title);
holder.detail = (TextView) view.findViewById(R.id.row_detail);
holder.imageView = (ImageView) view.findViewById(R.id.row_icon);
view.setTag(holder);
} else {
holder = (ViewHolder) recycledView.getTag();
holder.imageView.setImageDrawable(null);
view = recycledView;
}
if (selectedPosition == i) {
holder.row.setBackgroundColor(Color.CYAN);
} else {
holder.row.setBackgroundColor(Color.WHITE);
}
holder.text.setText(MARS_IMAGES.getMission().getLabelText(EVERNOTE.getNote(i)));
holder.detail.setText(MARS_IMAGES.getMission().getDetailText(EVERNOTE.getNote(i)));
String thumbnailURL = EVERNOTE.getThumbnailURL(i);
if (thumbnailURL != null) {
ImageLoader.getInstance().displayImage(thumbnailURL, holder.imageView);
}
if (i == EVERNOTE.getNotesCount() - 1 && EVERNOTE.hasNotesRemaining)
EVERNOTE.loadMoreImages(getActivity());
return view;
}
public void setCount(int count) {
mItemCount = count;
if (count == 0) {
setSelectedPosition(0);
}
}
}
class HeaderViewHolder {
TextView text;
}
class ViewHolder {
View row;
TextView text;
TextView detail;
ImageView imageView;
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(int imageIndex);
}
/**
* A dummy implementation of the {@link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(int imageIndex) {
}
};
} |
Java | public class CircularFieldOfView extends SmoothFieldOfView {
/** FOV half aperture angle. */
private final double halfAperture;
/** Scaled X axis defining FoV boundary. */
private final Vector3D scaledX;
/** Scaled Y axis defining FoV boundary. */
private final Vector3D scaledY;
/** Scaled Z axis defining FoV boundary. */
private final Vector3D scaledZ;
/** Build a new instance.
* @param center direction of the FOV center, in spacecraft frame
* @param halfAperture FOV half aperture angle
* @param margin angular margin to apply to the zone (if positive,
* the Field Of View will consider points slightly outside of the
* zone are still visible)
*/
public CircularFieldOfView(final Vector3D center, final double halfAperture,
final double margin) {
super(center, center.orthogonal(), margin);
this.halfAperture = halfAperture;
// precompute utility vectors for walking around the FoV
final SinCos sc = FastMath.sinCos(halfAperture);
scaledX = new Vector3D(sc.sin(), getX());
scaledY = new Vector3D(sc.sin(), getY());
scaledZ = new Vector3D(sc.cos(), getZ());
}
/** get the FOV half aperture angle.
* @return FOV half aperture angle
*/
public double getHalfAperture() {
return halfAperture;
}
/** {@inheritDoc} */
@Override
public double offsetFromBoundary(final Vector3D lineOfSight, final double angularRadius,
final VisibilityTrigger trigger) {
return Vector3D.angle(getCenter(), lineOfSight) - halfAperture +
trigger.radiusCorrection(angularRadius) - getMargin();
}
/** {@inheritDoc} */
@Override
public Vector3D projectToBoundary(final Vector3D lineOfSight) {
return directionAt(FastMath.atan2(Vector3D.dotProduct(lineOfSight, getY()),
Vector3D.dotProduct(lineOfSight, getX())));
}
/** {@inheritDoc} */
@Override
protected Vector3D directionAt(final double angle) {
final SinCos sc = FastMath.sinCos(angle);
return new Vector3D(sc.cos(), scaledX, sc.sin(), scaledY, 1.0, scaledZ);
}
} |
Java | public class ServiceManagerListener extends Listener {
private static final Logger LOG = LoggerFactory.getLogger(ServiceManagerListener.class);
private final ServerStatus serverStatus;
@Inject
public ServiceManagerListener(ServerStatus serverStatus) {
this.serverStatus = serverStatus;
}
@Override
public void healthy() {
LOG.info("Services are healthy");
serverStatus.start();
}
@Override
public void stopped() {
LOG.info("Services are now stopped.");
}
@Override
public void failure(Service service) {
// do not log the failure here again, the ServiceManager itself does so already on Level ERROR.
serverStatus.fail();
}
} |
Java | public class FirebaseService extends Service {
public static int CHAT_MESSAGE_NOTIFICATION_ID = 007;
public static boolean isRunning = false;
public static int nMsg = 0;
int user;
FirebaseDatabase database;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand", "Starting service...");
if (intent != null) user = intent.getIntExtra("id", 0);
else user = Utils.getLoggedUserId(getApplicationContext());
database = FirebaseDatabase.getInstance();
if (!isRunning) {
addEventListenerForChat();
isRunning = true;
}
//addEventListenerForChat();
return START_STICKY;
}
private void addEventListenerForChat() {
DatabaseReference ref = database.getReference("mensajes2");
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("onChildAdded (service)", dataSnapshot.getValue().toString()+"");
Mensaje mensaje = dataSnapshot.getValue(Mensaje.class);
if (mensaje.getIdSender() == user || mensaje.getIdReceiver() == user) {
if (mensaje != null && mensaje.getIdReceiver() == user && !mensaje.isVisto()
&& !App.isChatOpen) {
Log.d("Debug", "Se mostrara notificacion de mensaje");
showNotificationForMessage(mensaje);
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d("onChildChanged(service)", dataSnapshot.getValue().toString()+"");
Mensaje mensaje = dataSnapshot.getValue(Mensaje.class);
if (mensaje.getIdSender() == user || mensaje.getIdReceiver() == user) {
if (mensaje != null && mensaje.getIdReceiver() == user && !mensaje.isVisto()
&& !App.isChatOpen) {
Log.d("Debug", "Se mostrara notificacion de mensaje");
showNotificationForMessage(mensaje);
}
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showNotificationForMessage(Mensaje m) {
ChatConfiguration conf = App.context.getConfiguration();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(conf.getNotificationIcon())
.setContentTitle(conf.getNotificationTitle())
.setContentText(m.getMensaje())
.setNumber(++nMsg);
Intent resultIntent = new Intent(this, ChatActivity.class);
Bundle extras = new Bundle();
extras.putInt("id", m.getIdReceiver());
extras.putInt("receiver", m.getIdSender());
resultIntent.putExtras(extras);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
CHAT_MESSAGE_NOTIFICATION_ID,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
//int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
Notification notif = mBuilder.build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
mNotifyMgr.notify(CHAT_MESSAGE_NOTIFICATION_ID, mBuilder.build());
Utils.vibrate(this);
//if (Utils.vibrateOnNotification(getApplicationContext())) Utils.vibrate(this);
}
} |
Java | public class DataSourceValidationLayer implements ValidationLayer {
/* our log stream */
private static Logger LOG = Logger
.getLogger(DataSourceValidationLayer.class.getName());
/* our data source */
private DataSource dataSource = null;
/* should we quote product_type_id? */
private boolean quoteFields = false;
/**
* <p>
* Default Constructor
* </p>.
*/
public DataSourceValidationLayer(DataSource ds, boolean fieldQuote) {
dataSource = ds;
quoteFields = fieldQuote;
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#addElement(org.apache.oodt.cas.filemgr.structs.Element)
*/
public void addElement(Element element) throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String addMetaElemSql = "INSERT INTO elements (element_name, dc_element, element_description) VALUES ('"
+ element.getElementName()
+ ", '"
+ element.getDCElement()
+ "', '" + element.getDescription() + "')";
LOG.log(Level.FINE, "addMetadataElement: Executing: "
+ addMetaElemSql);
statement.execute(addMetaElemSql);
String elementId = new String();
String getMetaIdSql = "SELECT MAX(element_id) AS max_id FROM elements";
LOG.log(Level.FINE, "addElement: Executing: " + getMetaIdSql);
rs = statement.executeQuery(getMetaIdSql);
while (rs.next()) {
elementId = String.valueOf(rs.getInt("max_id"));
}
element.setElementId(elementId);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG
.log(Level.WARNING, "Exception adding element "
+ element.getElementName() + ". Message: "
+ e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback addElement transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) {
}
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#modifyElement(org.apache.oodt.cas.filemgr.structs.Element)
*/
public void modifyElement(Element element) throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String elementSql = "UPDATE elements SET element_name = '"
+ element.getElementName() + "', dc_element='"
+ element.getDCElement() + "', " + "element_description='"
+ element.getDescription() + "' WHERE " + "element_id = "
+ element.getElementId();
LOG.log(Level.FINE, "modifyElement: Executing: " + elementSql);
statement.execute(elementSql);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception modifying element. Message: "
+ e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback modifyElement transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#removeElement(org.apache.oodt.cas.filemgr.structs.Element)
*/
public void removeElement(Element element) throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String deleteElementSql = "DELETE FROM elements WHERE element_id = "
+ element.getElementId();
LOG
.log(Level.FINE, "removeElement: Executing: "
+ deleteElementSql);
statement.execute(deleteElementSql);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception removing element. Message: "
+ e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback removeElement transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#addElementToProductType(org.apache.oodt.cas.filemgr.structs.ProductType,
* org.apache.oodt.cas.filemgr.structs.Element)
*/
public void addElementToProductType(ProductType type, Element element)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String addMetaElemSql = "INSERT INTO product_type_element_map (product_type_id, element_id) VALUES(";
if (quoteFields) {
addMetaElemSql += "'" + type.getProductTypeId() + "',";
} else {
addMetaElemSql += type.getProductTypeId() + ",";
}
addMetaElemSql += " " + element.getElementId() + ")";
LOG.log(Level.FINE, "addElementToProductType: Executing: "
+ addMetaElemSql);
statement.execute(addMetaElemSql);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception adding element "
+ element.getElementName() + " to product type "
+ type.getName() + " . Message: " + e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback addElementToProductType transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#removeElementFromProductType(org.apache.oodt.cas.filemgr.structs.ProductType,
* org.apache.oodt.cas.filemgr.structs.Element)
*/
public void removeElementFromProductType(ProductType type, Element element)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String deleteElemSql = "DELETE FROM product_type_element_map WHERE product_type_id = ";
if (quoteFields) {
deleteElemSql += "'" + type.getProductTypeId() + "'";
} else {
deleteElemSql += type.getProductTypeId();
}
deleteElemSql += " AND element_id = " + element.getElementId();
LOG.log(Level.FINE, "removeElementFromProductType: Executing: "
+ deleteElemSql);
statement.execute(deleteElemSql);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception removing element "
+ element.getElementName() + " from product type "
+ type.getName() + ". Message: " + e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback removeElementFromProductType transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
public void addParentToProductType(ProductType type, String parent)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String addParentInfoSql = "INSERT INTO sub_to_super_map (product_type_id, parent_id) VALUES(";
if (quoteFields) {
addParentInfoSql += "'" + type.getProductTypeId() + "','"
+ parent + "')";
} else {
addParentInfoSql += type.getProductTypeId() + "," + parent
+ ")";
}
LOG.log(Level.FINE, "addParentToProductType: Executing: "
+ addParentInfoSql);
statement.execute(addParentInfoSql);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING,
"Exception adding parent info to product type "
+ type.getName() + " . Message: " + e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback addParentToProductType transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
public void removeParentFromProductType(ProductType type, String parent)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
statement = conn.createStatement();
String deleteParSql = "DELETE FROM sub_to_super_map WHERE product_type_id = ";
if (quoteFields) {
deleteParSql += "'" + type.getProductTypeId()
+ "' AND parent_id ='" + parent + "'";
} else {
deleteParSql += type.getProductTypeId() + " AND parent_id ="
+ parent;
}
LOG.log(Level.FINE, "removeParentFromProductType: Executing: "
+ deleteParSql);
statement.execute(deleteParSql);
conn.commit();
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING,
"Exception removing parent from product type "
+ type.getName() + ". Message: " + e.getMessage());
try {
conn.rollback();
} catch (SQLException e2) {
LOG.log(Level.SEVERE,
"Unable to rollback removeParentFromProductType transaction. Message: "
+ e2.getMessage());
}
throw new ValidationLayerException(e.getMessage());
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#getElements(org.apache.oodt.cas.filemgr.structs.ProductType)
*/
public List<Element> getElements(ProductType type)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
List<Element> elements = null;
elements = new Vector<Element>();
String currProduct = type.getProductTypeId();
while (currProduct != null) {
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
String elementSql = "SELECT elements.* from elements, product_type_element_map WHERE product_type_element_map.product_type_id = ";
if (quoteFields) {
elementSql += "'" + currProduct + "'";
} else {
elementSql += currProduct;
}
elementSql += " AND product_type_element_map.element_id = elements.element_id";
LOG.log(Level.FINE, "getElements: Executing: " + elementSql);
rs = statement.executeQuery(elementSql);
while (rs.next()) {
Element element = DbStructFactory.getElement(rs);
elements.add(element);
}
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception reading elements. Message: "
+ e.getMessage());
throw new ValidationLayerException(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) {
}
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
// advance to the product parent
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
String getParentSql = "SELECT parent_id from sub_to_super_map where product_type_id = ";
if (quoteFields) {
getParentSql += "'" + currProduct + "'";
} else {
getParentSql += currProduct;
}
LOG.log(Level.FINE, "getElements: Executing: " + getParentSql);
rs = statement.executeQuery(getParentSql);
currProduct = null;
while (rs.next()) {
currProduct = DbStructFactory.getParent(rs);
}
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING,
"Exception reading product parent. Message: "
+ e.getMessage());
throw new ValidationLayerException(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) {
}
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
}
return elements;
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#getElements()
*/
public List<Element> getElements() throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
List<Element> elements = null;
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
String dataTypeSql = "SELECT * from elements";
LOG.log(Level.FINE, "getElements: Executing: " + dataTypeSql);
rs = statement.executeQuery(dataTypeSql);
elements = new Vector<Element>();
while (rs.next()) {
Element element = DbStructFactory.getElement(rs);
LOG.log(Level.FINE, "getElements: adding element: "
+ element.getElementName());
elements.add(element);
}
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception reading elements. Message: "
+ e.getMessage());
throw new ValidationLayerException(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) {
}
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
return elements;
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#getElementById(java.lang.String)
*/
public Element getElementById(String elementId)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
Element element = null;
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
String elementSql = "SELECT * from elements WHERE element_id = "
+ elementId;
LOG.log(Level.FINE, "getElementById: Executing: " + elementSql);
rs = statement.executeQuery(elementSql);
while (rs.next()) {
element = DbStructFactory.getElement(rs);
LOG.log(Level.FINE, "getElementById: adding element: "
+ element.getElementName());
}
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception reading element. Message: "
+ e.getMessage());
throw new ValidationLayerException(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) {
}
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
return element;
}
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.filemgr.validation.ValidationLayer#getElementByName(java.lang.String)
*/
public Element getElementByName(String elementName)
throws ValidationLayerException {
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
Element element = null;
try {
conn = dataSource.getConnection();
statement = conn.createStatement();
String elementSql = "SELECT * from elements WHERE element_name = "
+ elementName;
LOG.log(Level.FINE, "getElementByName: Executing: " + elementSql);
rs = statement.executeQuery(elementSql);
while (rs.next()) {
element = DbStructFactory.getElement(rs);
LOG.log(Level.FINE, "getElementByName: adding element: "
+ element.getElementName());
}
} catch (Exception e) {
e.printStackTrace();
LOG.log(Level.WARNING, "Exception reading element. Message: "
+ e.getMessage());
throw new ValidationLayerException(e.getMessage());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ignore) {
}
rs = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ignore) {
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
conn = null;
}
}
return element;
}
} |
Java | public class ReadableJslipcFileChannel extends AbstractJslipcFileChannel implements
ReadableJslipcByteChannel, InterruptibleChannel {
/**
* Creates ReadableJslipcFileChannel based on the given file.
*
* @param file
* @throws IOException
*/
public ReadableJslipcFileChannel(File file) throws IOException {
super(file, "r");
}
@Override
public int read(ByteBuffer dst) throws IOException {
checkClosed();
int count = getFileChannel().read(dst);
if (count == -1 && getState() != JslipcChannelState.ClosedByPeer) {
return 0;
}
return count;
}
} |
Java | public class TemplateLayout extends FrameLayout {
/**
* The container of the actual content. This will be a view in the template, which child views
* will be added to when {@link #addView(View)} is called.
*/
private ViewGroup mContainer;
private Map<Class<? extends Mixin>, Mixin> mMixins = new HashMap<>();
public TemplateLayout(Context context, int template, int containerId) {
super(context);
init(template, containerId, null, R.attr.suwLayoutTheme);
}
public TemplateLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(0, 0, attrs, R.attr.suwLayoutTheme);
}
@TargetApi(VERSION_CODES.HONEYCOMB)
public TemplateLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(0, 0, attrs, defStyleAttr);
}
// All the constructors delegate to this init method. The 3-argument constructor is not
// available in LinearLayout before v11, so call super with the exact same arguments.
private void init(int template, int containerId, AttributeSet attrs, int defStyleAttr) {
final TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.SuwTemplateLayout, defStyleAttr, 0);
if (template == 0) {
template = a.getResourceId(R.styleable.SuwTemplateLayout_android_layout, 0);
}
if (containerId == 0) {
containerId = a.getResourceId(R.styleable.SuwTemplateLayout_suwContainer, 0);
}
inflateTemplate(template, containerId);
a.recycle();
}
/**
* Registers a mixin with a given class. This method should be called in the constructor.
*
* @param cls The class to register the mixin. In most cases, {@code cls} is the same as
* {@code mixin.getClass()}, but {@code cls} can also be a super class of that. In
* the latter case the the mixin must be retrieved using {@code cls} in
* {@link #getMixin(Class)}, not the subclass.
* @param mixin The mixin to be registered.
* @param <M> The class of the mixin to register. This is the same as {@code cls}
*/
protected <M extends Mixin> void registerMixin(Class<M> cls, M mixin) {
mMixins.put(cls, mixin);
}
/**
* Same as {@link android.view.View#findViewById(int)}, but may include views that are managed
* by this view but not currently added to the view hierarchy. e.g. recycler view or list view
* headers that are not currently shown.
*/
// Returning generic type is the common pattern used for findViewBy* methods
@SuppressWarnings("TypeParameterUnusedInFormals")
public <T extends View> T findManagedViewById(int id) {
return findViewById(id);
}
/**
* Get a {@link Mixin} from this template registered earlier in
* {@link #registerMixin(Class, Mixin)}.
*
* @param cls The class marker of Mixin being requested. The actual Mixin returned may be a
* subclass of this marker. Note that this must be the same class as registered in
* {@link #registerMixin(Class, Mixin)}, which is not necessarily the
* same as the concrete class of the instance returned by this method.
* @param <M> The type of the class marker.
* @return The mixin marked by {@code cls}, or null if the template does not have a matching
* mixin.
*/
@SuppressWarnings("unchecked")
public <M extends Mixin> M getMixin(Class<M> cls) {
return (M) mMixins.get(cls);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
mContainer.addView(child, index, params);
}
private void addViewInternal(View child) {
super.addView(child, -1, generateDefaultLayoutParams());
}
private void inflateTemplate(int templateResource, int containerId) {
final LayoutInflater inflater = LayoutInflater.from(getContext());
final View templateRoot = onInflateTemplate(inflater, templateResource);
addViewInternal(templateRoot);
mContainer = findContainer(containerId);
if (mContainer == null) {
throw new IllegalArgumentException("Container cannot be null in TemplateLayout");
}
onTemplateInflated();
}
/**
* This method inflates the template. Subclasses can override this method to customize the
* template inflation, or change to a different default template. The root of the inflated
* layout should be returned, and not added to the view hierarchy.
*
* @param inflater A LayoutInflater to inflate the template.
* @param template The resource ID of the template to be inflated, or 0 if no template is
* specified.
* @return Root of the inflated layout.
*/
protected View onInflateTemplate(LayoutInflater inflater, @LayoutRes int template) {
return inflateTemplate(inflater, 0, template);
}
/**
* Inflate the template using the given inflater and theme. The fallback theme will be applied
* to the theme without overriding the values already defined in the theme, but simply providing
* default values for values which have not been defined. This allows templates to add
* additional required theme attributes without breaking existing clients.
*
* <p>In general, clients should still set the activity theme to the corresponding theme in
* setup wizard lib, so that the content area gets the correct styles as well.
*
* @param inflater A LayoutInflater to inflate the template.
* @param fallbackTheme A fallback theme to apply to the template. If the values defined in the
* fallback theme is already defined in the original theme, the value in
* the original theme takes precedence.
* @param template The layout template to be inflated.
* @return Root of the inflated layout.
*
* @see FallbackThemeWrapper
*/
protected final View inflateTemplate(LayoutInflater inflater, @StyleRes int fallbackTheme,
@LayoutRes int template) {
if (template == 0) {
throw new IllegalArgumentException("android:layout not specified for TemplateLayout");
}
if (fallbackTheme != 0) {
inflater = LayoutInflater.from(
new FallbackThemeWrapper(inflater.getContext(), fallbackTheme));
}
return inflater.inflate(template, this, false);
}
protected ViewGroup findContainer(int containerId) {
if (containerId == 0) {
// Maintain compatibility with the deprecated way of specifying container ID.
containerId = getContainerId();
}
return (ViewGroup) findViewById(containerId);
}
/**
* This is called after the template has been inflated and added to the view hierarchy.
* Subclasses can implement this method to modify the template as necessary, such as caching
* views retrieved from findViewById, or other view operations that need to be done in code.
* You can think of this as {@link View#onFinishInflate()} but for inflation of the
* template instead of for child views.
*/
protected void onTemplateInflated() {
}
/**
* @return ID of the default container for this layout. This will be used to find the container
* ViewGroup, which all children views of this layout will be placed in.
* @deprecated Override {@link #findContainer(int)} instead.
*/
@Deprecated
protected int getContainerId() {
return 0;
}
/* Animator support */
private float mXFraction;
private ViewTreeObserver.OnPreDrawListener mPreDrawListener;
/**
* Set the X translation as a fraction of the width of this view. Make sure this method is not
* stripped out by proguard when using this with {@link android.animation.ObjectAnimator}. You
* may need to add
* <code>
* -keep @androidx.annotation.Keep class *
* </code>
* to your proguard configuration if you are seeing mysterious {@link NoSuchMethodError} at
* runtime.
*/
@Keep
@TargetApi(VERSION_CODES.HONEYCOMB)
public void setXFraction(float fraction) {
mXFraction = fraction;
final int width = getWidth();
if (width != 0) {
setTranslationX(width * fraction);
} else {
// If we haven't done a layout pass yet, wait for one and then set the fraction before
// the draw occurs using an OnPreDrawListener. Don't call translationX until we know
// getWidth() has a reliable, non-zero value or else we will see the fragment flicker on
// screen.
if (mPreDrawListener == null) {
mPreDrawListener = new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(mPreDrawListener);
setXFraction(mXFraction);
return true;
}
};
getViewTreeObserver().addOnPreDrawListener(mPreDrawListener);
}
}
}
/**
* Return the X translation as a fraction of the width, as previously set in
* {@link #setXFraction(float)}.
*
* @see #setXFraction(float)
*/
@Keep
@TargetApi(VERSION_CODES.HONEYCOMB)
public float getXFraction() {
return mXFraction;
}
} |
Java | public class TargetInstanceProfileCommand extends ProfileCommand {
private boolean overrideTarget = false;
/**
* @return the overrideTarget
*/
public boolean isOverrideTarget() {
return overrideTarget;
}
/**
* @param overrideTarget the overrideTarget to set
*/
public void setOverrideTarget(boolean overrideTarget) {
this.overrideTarget = overrideTarget;
}
} |
Java | public class MethodClient {
protected final StreamObserver<? extends MessageLite> defaultObserver;
private final RpcManager rpcs;
private final PendingRpc rpc;
MethodClient(RpcManager rpcs, PendingRpc rpc, StreamObserver<MessageLite> defaultObserver) {
this.rpcs = rpcs;
this.rpc = rpc;
this.defaultObserver = defaultObserver;
}
public final Method method() {
return rpc.method();
}
/** Gives implementations access to the RpcManager shared with the Client. */
protected final RpcManager rpcs() {
return rpcs;
}
/** Gives implementations access to the PendingRpc this MethodClient represents. */
protected final PendingRpc rpc() {
return rpc;
}
/** Invokes a unary RPC. Uses the default StreamObserver for RPC events. */
public Call invokeUnary(MessageLite request) throws ChannelOutputException {
return invokeUnary(request, defaultObserver());
}
/** Invokes a unary RPC. Uses the provided StreamObserver for RPC events. */
public Call invokeUnary(MessageLite request, StreamObserver<? extends MessageLite> observer)
throws ChannelOutputException {
checkCallType(Method.Type.UNARY);
return StreamObserverCall.start(rpcs(), rpc(), observer, request);
}
/** Invokes a unary RPC with a future that collects the response. */
public <ResponseT extends MessageLite> Call.UnaryFuture<ResponseT> invokeUnaryFuture(
MessageLite request) {
checkCallType(Method.Type.UNARY);
return new UnaryResponseFuture<>(rpcs(), rpc(), request);
}
/**
* Starts a unary RPC, ignoring any errors that occur when opening. This can be used to start
* listening to responses to an RPC before the RPC server is available.
*
* <p>The RPC remains open until it is completed by the server with a response or error packet or
* cancelled.
*/
public Call openUnary(MessageLite request, StreamObserver<? extends MessageLite> observer) {
checkCallType(Method.Type.UNARY);
return StreamObserverCall.open(rpcs(), rpc(), observer, request);
}
/** Invokes a server streaming RPC. Uses the default StreamObserver for RPC events. */
public Call invokeServerStreaming(MessageLite request) throws ChannelOutputException {
return invokeServerStreaming(request, defaultObserver());
}
/** Invokes a server streaming RPC. Uses the provided StreamObserver for RPC events. */
public Call invokeServerStreaming(MessageLite request,
StreamObserver<? extends MessageLite> observer) throws ChannelOutputException {
checkCallType(Method.Type.SERVER_STREAMING);
return StreamObserverCall.start(rpcs(), rpc(), observer, request);
}
/** Invokes a server streaming RPC with a future that collects the responses. */
public Call.ServerStreamingFuture invokeServerStreamingFuture(
MessageLite request, Consumer<? extends MessageLite> onNext) {
checkCallType(Method.Type.SERVER_STREAMING);
return new StreamResponseFuture<>(rpcs(), rpc(), onNext, request);
}
/**
* Starts a server streaming RPC, ignoring any errors that occur when opening. This can be used to
* start listening to responses to an RPC before the RPC server is available.
*
* <p>The RPC remains open until it is completed by the server with a response or error packet or
* cancelled.
*/
public Call openServerStreaming(
MessageLite request, StreamObserver<? extends MessageLite> observer) {
checkCallType(Method.Type.SERVER_STREAMING);
return StreamObserverCall.open(rpcs(), rpc(), observer, request);
}
/** Invokes a client streaming RPC. Uses the default StreamObserver for RPC events. */
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT> invokeClientStreaming()
throws ChannelOutputException {
return invokeClientStreaming(defaultObserver());
}
/** Invokes a client streaming RPC. Uses the provided StreamObserver for RPC events. */
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT> invokeClientStreaming(
StreamObserver<? extends MessageLite> observer) throws ChannelOutputException {
checkCallType(Method.Type.CLIENT_STREAMING);
return StreamObserverCall.start(rpcs(), rpc(), observer, null);
}
/** Invokes a client streaming RPC with a future that collects the response. */
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT>
invokeClientStreamingFuture() {
checkCallType(Method.Type.CLIENT_STREAMING);
return new UnaryResponseFuture<>(rpcs(), rpc(), null);
}
/**
* Starts a client streaming RPC, ignoring any errors that occur when opening. This can be used to
* start listening to responses to an RPC before the RPC server is available.
*
* <p>The RPC remains open until it is completed by the server with a response or error packet or
* cancelled.
*/
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT> openClientStreaming(
StreamObserver<? extends MessageLite> observer) {
checkCallType(Method.Type.CLIENT_STREAMING);
return StreamObserverCall.open(rpcs(), rpc(), observer, null);
}
/** Invokes a bidirectional streaming RPC. Uses the default StreamObserver for RPC events. */
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT>
invokeBidirectionalStreaming() throws ChannelOutputException {
return invokeBidirectionalStreaming(defaultObserver());
}
/** Invokes a bidirectional streaming RPC. Uses the provided StreamObserver for RPC events. */
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT> invokeBidirectionalStreaming(
StreamObserver<? extends MessageLite> observer) throws ChannelOutputException {
checkCallType(Method.Type.BIDIRECTIONAL_STREAMING);
return StreamObserverCall.start(rpcs(), rpc(), observer, null);
}
/** Invokes a bidirectional streaming RPC with a future that finishes when the RPC finishes. */
public <RequestT extends MessageLite, ResponseT extends MessageLite>
Call.BidirectionalStreamingFuture<RequestT> invokeBidirectionalStreamingFuture(
Consumer<ResponseT> onNext) {
checkCallType(Method.Type.BIDIRECTIONAL_STREAMING);
return new StreamResponseFuture<>(rpcs(), rpc(), onNext, null);
}
/**
* Starts a bidirectional streaming RPC, ignoring any errors that occur when opening. This can be
* used to start listening to responses to an RPC before the RPC server is available.
*
* <p>The RPC remains open until it is completed by the server with a response or error packet or
* cancelled.
*/
public <RequestT extends MessageLite> Call.ClientStreaming<RequestT> openBidirectionalStreaming(
StreamObserver<? extends MessageLite> observer) {
checkCallType(Method.Type.BIDIRECTIONAL_STREAMING);
return StreamObserverCall.open(rpcs(), rpc(), observer, null);
}
@SuppressWarnings("unchecked")
private <ResponseT extends MessageLite> StreamObserver<ResponseT> defaultObserver() {
return (StreamObserver<ResponseT>) defaultObserver;
}
private void checkCallType(Method.Type expected) {
if (!rpc().method().type().equals(expected)) {
throw new UnsupportedOperationException(String.format(
"%s is a %s method, but it was invoked as a %s method. RPCs must be invoked by the"
+ " appropriate invoke function.",
method().fullName(),
method().type().sentenceName(),
expected.sentenceName()));
}
}
} |
Java | public class HtmlFeatureParserTest {
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
@Test
public void JSoupElementsAddedTest() throws Exception {
String testHtml = "<b>test<p></b>";
String baseUri = "http://example.com/dummy.html";
//
ByteArrayInputStream stream = new ByteArrayInputStream(
testHtml.getBytes());
stream.mark(100000);
Parser parser = Parser.xmlParser();
parser.setTrackErrors(1000);
Document doc = Jsoup.parse(stream, null, baseUri, parser);
System.out.println("Parsed as:\n" + doc);
System.out.println("Got " + parser.getErrors().size()
+ " under isTrackErrors = " + parser.isTrackErrors());
for (ParseError err : parser.getErrors()) {
System.out.println("Got: " + err);
}
// Also run in through the handler class:
stream.reset();
innerBasicParseTest(stream, baseUri, 2);
}
@Test
public void testNormalise() {
final String[][] TESTS = new String[][] { // Expected, input
// {"http://example.org", "http://www.example.org"},
{"http://example.org/foo", "http://www.example.org/foo"},
{"http://example.org", "http://example.org"},
{"http://example.org", "http://example.org?"},
//{"http://example.org", "https://example.org?"},
{"http://example.org", "http://[email protected]"},
{"http://example.org/foo", "http://[email protected]/foo"},
// {"http://example.org", "http://[email protected]"},
{"http://example.org", "http://eXample.org"},
{"http://example.org", "http://example.ORG"},
// {"http://example.org", "http://example.org/"},
// {"http://example.org", "http://example.org/index.html"}
};
Map<String, String> normMap = new HashMap<String, String>();
normMap.put(HtmlFeatureParser.CONF_LINKS_NORMALISE, "true");
HtmlFeatureParser normParser = new HtmlFeatureParser(ConfigFactory.parseMap(normMap));
normMap.put(HtmlFeatureParser.CONF_LINKS_NORMALISE, "false");
HtmlFeatureParser skipParser = new HtmlFeatureParser(ConfigFactory.parseMap(normMap));
for (String[] test: TESTS) {
Assert.assertEquals("Normalisation of '" + test[1] + "'",
test[0], normParser.normaliseLink(test[1]));
Assert.assertEquals("Non-normalisation of '" + test[1] + "'",
test[1], skipParser.normaliseLink(test[1]));
}
}
private static void printMetadata(Metadata metadata) {
for (String name : metadata.names()) {
for (String value : metadata.getValues(name)) {
System.out.println(name + ": " + value);
}
}
}
private void innerBasicParseTest(InputStream stream, String uri,
int numElements)
throws IOException, SAXException, TikaException {
HtmlFeatureParser hfp = new HtmlFeatureParser();
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, uri);
hfp.parse(stream, null, metadata, null);
printMetadata(metadata);
// for (ParseError err : hfp.getParseErrors()) {
// System.out.println("PARSE-ERROR: " + err);
// }
Assert.assertEquals("Number of distinct elements was wrong,",
numElements,
metadata.getValues(HtmlFeatureParser.DISTINCT_ELEMENTS).length );
}
/**
* Test method for
* {@link uk.bl.wa.parsers.HtmlFeatureParser#parse(java.io.InputStream, org.xml.sax.ContentHandler, org.apache.tika.metadata.Metadata, org.apache.tika.parser.ParseContext)}
* .
*
* @throws Exception
*/
@Test
public void testParseInputStreamContentHandlerMetadataParseContext()
throws Exception {
String baseUri = "http://en.wikipedia.org/wiki/Mona_Lisa";
File ml = new File(
"src/test/resources/wikipedia-mona-lisa/Mona_Lisa.html");
URL url = ml.toURI().toURL();
innerBasicParseTest(url.openStream(), baseUri, 43);
}
} |
Java | public class DirectoryClassPathRoot implements ClassPathRoot, IOHeavyRoot {
private final File root;
public DirectoryClassPathRoot(final File root) {
this.root = root;
}
@Override
public InputStream getData(final String classname) throws IOException {
final String filename = classname.replace('.', File.separatorChar).concat(
".class");
final File file = new File(this.root, filename);
if (file.canRead()) {
return new FileInputStream(file);
} else {
return null;
}
}
@Override
public URL getResource(final String name) throws MalformedURLException {
final File f = new File(this.root, name);
if (f.canRead()) {
// magically work around encoding issues
return f.toURI().toURL();
} else {
return null;
}
}
@Override
public Collection<String> classNames() {
return classNames(this.root);
}
private Collection<String> classNames(final File file) {
final List<String> classNames = new LinkedList<>();
for (final File f : file.listFiles()) {
if (f.isDirectory()) {
classNames.addAll(classNames(f));
} else if (f.getName().endsWith(".class")) {
classNames.add(fileToClassName(f));
}
}
return classNames;
}
private String fileToClassName(final File f) {
return f
.getAbsolutePath()
.substring(this.root.getAbsolutePath().length() + 1,
(f.getAbsolutePath().length() - ".class".length()))
.replace(File.separatorChar, '.');
}
@Override
public Optional<String> cacheLocation() {
return Optional.ofNullable(this.root.getAbsolutePath());
}
} |
Java | public class Ssp extends User implements Serializable {
private Integer id;
private String nome;
private String provincia;
private String abbreviazione;
private String numeroTelefono;
private Integer numeroPazienti;
private Integer numeroMediciBase;
private Integer numeroMediciSpecialisti;
public Ssp() {
super();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Ssp)) return false;
if (!super.equals(o)) return false;
Ssp ssp = (Ssp) o;
return getId().equals(ssp.getId()) &&
getNome().equals(ssp.getNome()) &&
getProvincia().equals(ssp.getProvincia()) &&
getNumeroTelefono().equals(ssp.getNumeroTelefono());
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getId(), getNome(), getProvincia(), getNumeroTelefono());
}
public Integer getNumeroPazienti() {
return numeroPazienti;
}
public void setNumeroPazienti(Integer numeroPazienti) {
this.numeroPazienti = numeroPazienti;
}
public Integer getNumeroMediciBase() {
return numeroMediciBase;
}
public void setNumeroMediciBase(Integer numeroMediciBase) {
this.numeroMediciBase = numeroMediciBase;
}
public Integer getNumeroMediciSpecialisti() {
return numeroMediciSpecialisti;
}
public void setNumeroMediciSpecialisti(Integer numeroMediciSpecialisti) {
this.numeroMediciSpecialisti = numeroMediciSpecialisti;
}
public String getAbbreviazione() {
return abbreviazione;
}
public void setAbbreviazione(String abbreviazione) {
this.abbreviazione = abbreviazione;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getProvincia() {
return provincia;
}
public void setProvincia(String provincia) {
this.provincia = provincia;
}
public String getNumeroTelefono() {
return numeroTelefono;
}
public void setNumeroTelefono(String numeroTelefono) {
this.numeroTelefono = numeroTelefono;
}
} |
Java | public final class DBConf{
private static String databaseURL = "";
private static String databaseUName = "";
private static String databasePWord = "";
private static String databaseName = "";
private static String testDatabaseURL = "";
private static String testDatabaseUName = "";
private static String testDatabasePWord = "";
private static String testDatabaseName = "";
private static boolean isNotTest = false; // Do not change this value, change them in dbconfig.xml
private static boolean isProductProtectLockOffline = false; // In production: set true ; In test: set false
private static boolean isTestsuiteOffline = false; // Test suite offline: set true ; Test suite online: set false
private static boolean isGpinterfaceOffline = false; // Testing gpinterface offline: set true ; Test suite online: set false
private static Connection connection;
static {
ReadConfigXml reader = new ReadConfigXml("dbconfig.xml"); // ��ȡxml�ļ������ݿ������Ϣ
databaseURL = reader.getUrl();
databaseName = reader.getDataBase();
databaseUName = reader.getUserName();
databasePWord = reader.getPassWord();
testDatabaseURL = reader.getTestUrl();
testDatabaseName = reader.getTestDataBase();
testDatabaseUName = reader.getTestUserName();
testDatabasePWord = reader.getTestPassWord();
isNotTest = reader.isNotTest();
isTestsuiteOffline = reader.isTestsuiteOffline();
isProductProtectLockOffline = reader.isProductProtectLockOffline();
isGpinterfaceOffline = reader.isGpinterfaceOffline();
}
public static Connection initDB() throws IOException{
try {
String tdatabaseURL ="";
String tdatabaseUName ="";
String tdatabasePWord = "";
String tdatabaseName = "";
if (isNotTest && isProductProtectLockOffline){
tdatabaseURL = databaseURL;
tdatabaseUName = databaseUName;
tdatabasePWord = databasePWord;
tdatabaseName = databaseName;
} else {
tdatabaseURL = testDatabaseURL;
tdatabaseUName = testDatabaseUName;
tdatabasePWord = testDatabasePWord;
tdatabaseName = testDatabaseName;
}
Class.forName("com.mysql.jdbc.Driver");
String url = tdatabaseURL + tdatabaseName;
connection = DriverManager.getConnection(url,tdatabaseUName,tdatabasePWord);
} catch (Exception e){
throw new IOException(e.getMessage());
}
DBConf.setConnection(connection);
return connection;
}
public static void closeDB(Connection connection) {
try {
connection.close();
connection = null;
} catch (Exception e){
}
}
public static void switchToTest(){
isNotTest = false;
}
public static void switchToProduction(){
isNotTest = true;
}
public static Connection getConnection() {
try {
return initDB();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static void setConnection(Connection connection) {
DBConf.connection = connection;
}
public static boolean isTestsuiteOffline() {
return isTestsuiteOffline;
}
public static boolean isGpinterfaceOffline() {
return isGpinterfaceOffline;
}
} |
Java | @BuiltInFunction(name=TransactionProviderNameFunction.NAME, args= {
@Argument(allowedTypes= PInteger.class)} )
public class TransactionProviderNameFunction extends ScalarFunction {
public static final String NAME = "TransactionProviderName";
public TransactionProviderNameFunction() {
}
public TransactionProviderNameFunction(List<Expression> children) throws SQLException {
super(children);
}
@Override
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
Expression child = children.get(0);
if (!child.evaluate(tuple, ptr)) {
return false;
}
if (ptr.getLength() == 0) {
return true;
}
int code = PTinyint.INSTANCE.getCodec().decodeByte(ptr, child.getSortOrder());
TransactionFactory.Provider provider = TransactionFactory.Provider.fromCode(code);
ptr.set(PVarchar.INSTANCE.toBytes(provider.name()));
return true;
}
@Override
public PDataType getDataType() {
return PVarchar.INSTANCE;
}
@Override
public String getName() {
return NAME;
}
} |
Java | @SuppressWarnings({"WeakerAccess", "unused"})
public class SharedPreferencesStorage implements Storage {
private static final String SHARED_PREFERENCES_NAME = "com.auth0.authentication.storage";
private final SharedPreferences sp;
/**
* Creates a new {@link Storage} that uses {@link SharedPreferences} in Context.MODE_PRIVATE to store values.
*
* @param context a valid context
*/
public SharedPreferencesStorage(@NonNull Context context) {
this(context, SHARED_PREFERENCES_NAME);
}
/**
* Creates a new {@link Storage} that uses {@link SharedPreferences} in Context.MODE_PRIVATE to store values.
*
* @param context a valid context
* @param sharedPreferencesName the preferences file name
*/
public SharedPreferencesStorage(@NonNull Context context, @NonNull String sharedPreferencesName) {
if (TextUtils.isEmpty(sharedPreferencesName)) {
throw new IllegalArgumentException("The SharedPreferences name is invalid.");
}
sp = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
}
@Override
public void store(@NonNull String name, @Nullable Long value) {
if (value == null) {
sp.edit().remove(name).apply();
} else {
sp.edit().putLong(name, value).apply();
}
}
@Override
public void store(@NonNull String name, @Nullable Integer value) {
if (value == null) {
sp.edit().remove(name).apply();
} else {
sp.edit().putInt(name, value).apply();
}
}
@Override
public void store(@NonNull String name, @Nullable String value) {
if (value == null) {
sp.edit().remove(name).apply();
} else {
sp.edit().putString(name, value).apply();
}
}
@Override
public void store(@NonNull String name, @Nullable Boolean value) {
if (value == null) {
sp.edit().remove(name).apply();
} else {
sp.edit().putBoolean(name, value).apply();
}
}
@Nullable
@Override
public Long retrieveLong(@NonNull String name) {
if (!sp.contains(name)) {
return null;
}
return sp.getLong(name, 0);
}
@Nullable
@Override
public String retrieveString(@NonNull String name) {
if (!sp.contains(name)) {
return null;
}
return sp.getString(name, null);
}
@Nullable
@Override
public Integer retrieveInteger(@NonNull String name) {
if (!sp.contains(name)) {
return null;
}
return sp.getInt(name, 0);
}
@Nullable
@Override
public Boolean retrieveBoolean(@NonNull String name) {
if (!sp.contains(name)) {
return null;
}
return sp.getBoolean(name, false);
}
@Override
public void remove(@NonNull String name) {
sp.edit().remove(name).apply();
}
} |
Java | public class FutureContext {
private static InternalThreadLocal<FutureContext> futureTL = new InternalThreadLocal<FutureContext>() {
@Override
protected FutureContext initialValue() {
return new FutureContext();
}
};
public static FutureContext getContext() {
return futureTL.get();
}
private CompletableFuture<?> future;
private CompletableFuture<?> compatibleFuture;
/**
* get future.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
return (CompletableFuture<T>) future;
}
/**
* set future.
*
* @param future
*/
public void setFuture(CompletableFuture<?> future) {
this.future = future;
}
@Deprecated
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompatibleCompletableFuture() {
return (CompletableFuture<T>) compatibleFuture;
}
/**
* Guarantee 'using org.apache.dubbo.rpc.RpcContext.getFuture() before proxy returns' can work, a typical scenario is:
* <pre>{@code
* public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* Future<Object> future = rpcContext.getFuture();
* if (future instanceof FutureAdapter) {
* ((FutureAdapter) future).getFuture().setCallback(new FinishSpanCallback(span));
* }
* ......
* }
* }
* }</pre>
*
* Start from 2.7.3, you don't have to get Future from RpcContext, we recommend using Result directly:
* <pre>{@code
* public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* result.getResponseFuture().whenComplete(new FinishSpanCallback(span));
* ......
* }
* }
* }</pre>
*
*/
@Deprecated
public void setCompatibleFuture(CompletableFuture<?> compatibleFuture) {
this.compatibleFuture = compatibleFuture;
if (compatibleFuture != null) {
this.setFuture(new FutureAdapter(compatibleFuture));
}
}
} |
Java | @Generated("com.querydsl.codegen.EntitySerializer")
public class QInvitedGuestEntity extends EntityPathBase<InvitedGuestEntity> {
private static final long serialVersionUID = -181233306L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QInvitedGuestEntity invitedGuestEntity = new QInvitedGuestEntity("invitedGuestEntity");
public final com.devonfw.application.mtsj.general.dataaccess.api.QApplicationPersistenceEntity _super = new com.devonfw.application.mtsj.general.dataaccess.api.QApplicationPersistenceEntity(this);
public final BooleanPath accepted = createBoolean("accepted");
public final QBookingEntity booking;
public final StringPath bookingId = createString("bookingId");
public final StringPath email = createString("email");
public final StringPath guestToken = createString("guestToken");
//inherited
public final StringPath id = _super.id;
//inherited
public final NumberPath<Integer> modificationCounter = _super.modificationCounter;
public final DateTimePath<java.time.Instant> modificationDate = createDateTime("modificationDate", java.time.Instant.class);
public final com.devonfw.application.mtsj.ordermanagement.dataaccess.api.QOrderEntity order;
public final StringPath orderId = createString("orderId");
public QInvitedGuestEntity(String variable) {
this(InvitedGuestEntity.class, forVariable(variable), INITS);
}
public QInvitedGuestEntity(Path<? extends InvitedGuestEntity> path) {
this(path.getType(), path.getMetadata(), path.getMetadata().isRoot() ? INITS : PathInits.DEFAULT);
}
public QInvitedGuestEntity(PathMetadata metadata) {
this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT);
}
public QInvitedGuestEntity(PathMetadata metadata, PathInits inits) {
this(InvitedGuestEntity.class, metadata, inits);
}
public QInvitedGuestEntity(Class<? extends InvitedGuestEntity> type, PathMetadata metadata, PathInits inits) {
super(type, metadata, inits);
this.booking = inits.isInitialized("booking") ? new QBookingEntity(forProperty("booking"), inits.get("booking")) : null;
this.order = inits.isInitialized("order") ? new com.devonfw.application.mtsj.ordermanagement.dataaccess.api.QOrderEntity(forProperty("order"), inits.get("order")) : null;
}
} |
Java | public class TreeController extends TilesAction
{
@Override
public ActionForward execute(
ComponentContext context,
ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
@SuppressWarnings("unchecked") Set<String> openClasses =
(Set<String>) session.getAttribute("openClasses");
if (openClasses == null) {
openClasses = new HashSet<String>();
openClasses.add("org.intermine.model.InterMineObject");
session.setAttribute("openClasses", openClasses);
}
ServletContext servletContext = session.getServletContext();
Model model = im.getModel();
String rootClass = (String) request.getAttribute("rootClass");
List<ClassDescriptor> rootClasses = new ArrayList<ClassDescriptor>();
if (rootClass != null) {
rootClasses.add(model.getClassDescriptorByName(rootClass));
} else {
rootClass = "org.intermine.model.InterMineObject";
rootClasses.add(model.getClassDescriptorByName(rootClass));
for (ClassDescriptor cld : model.getClassDescriptors()) {
if (cld.getSuperDescriptors().isEmpty() && (!"org.intermine.model.InterMineObject"
.equals(cld.getName()))) {
rootClasses.add(cld);
}
}
}
Map<?, ?> classCounts = (Map<?, ?>) servletContext.getAttribute("classCounts");
List<TreeNode> nodes = new ArrayList<TreeNode>();
List<String> empty = Collections.emptyList();
Iterator<ClassDescriptor> cldIter = rootClasses.iterator();
while (cldIter.hasNext()) {
ClassDescriptor cld = cldIter.next();
nodes.addAll(makeNodes(cld, openClasses, 0, classCounts, empty, !cldIter.hasNext()));
}
context.putAttribute("nodes", nodes);
return null;
}
/**
* Produce a list of tree nodes for a class and its children, marking as 'open' and recursing
* on any that appear on the openClasses list.
* @param parent the root class
* @param openClasses the Set of open classes
* @param depth the current depth from the root
* @param classCounts the classCounts attribute from the ServletContext
* @param structure a list of Strings - for definition see TreeNode.getStructure
* @param last true if this is the last sibling
* @return a List of nodes
*/
protected List<TreeNode> makeNodes(ClassDescriptor parent, Set<String> openClasses, int depth,
Map<?, ?> classCounts, List<String> structure, boolean last) {
List<String> newStructure = new ArrayList<String>(structure);
if (last) {
newStructure.add("ell");
} else {
newStructure.add("tee");
}
newStructure.remove(0);
List<TreeNode> nodes = new ArrayList<TreeNode>();
nodes.add(new TreeNode(parent, classCounts.get(parent.getName()).toString(),
depth, false, parent.getSubDescriptors().size() == 0,
openClasses.contains(parent.getName()), newStructure));
newStructure = new ArrayList<String>(structure);
if (last) {
newStructure.add("blank");
} else {
newStructure.add("straight");
}
if (openClasses.contains(parent.getName())) {
Set<ClassDescriptor> sortedClds = new TreeSet<ClassDescriptor>(
new Comparator<ClassDescriptor>() {
public int compare(ClassDescriptor c1, ClassDescriptor c2) {
return c1.getName().compareTo(c2.getName());
}
});
sortedClds.addAll(parent.getSubDescriptors());
Iterator<ClassDescriptor> cldIter = sortedClds.iterator();
while (cldIter.hasNext()) {
ClassDescriptor cld = cldIter.next();
nodes.addAll(makeNodes(cld, openClasses, depth + 1, classCounts, newStructure,
!cldIter.hasNext()));
}
}
return nodes;
}
} |
Java | public class Consts {
private static final Set<String> kwd = new HashSet<>();
public static final Set<String> KEYWORDS = Collections.unmodifiableSet(kwd);
static {
kwd.add("break");
kwd.add("else");
kwd.add("FALSE");
kwd.add("for");
kwd.add("function");
kwd.add("if");
kwd.add("in");
kwd.add("Inf");
kwd.add("NA");
kwd.add("NA_character_");
kwd.add("NA_complex_");
kwd.add("NA_integer_");
kwd.add("NA_real_");
kwd.add("NaN");
kwd.add("next");
kwd.add("NULL");
kwd.add("repeat");
kwd.add("TRUE");
kwd.add("while");
}
/* private to enforce static */
private Consts() {
}
} |
Java | public class BooleanExpression extends SQLExpression
{
boolean hasClosure = false;
/**
* Constructor for a boolean expression for the specified mapping using the specified SQL text.
* @param stmt The statement
* @param mapping the mapping associated to this expression
* @param sql The SQL text that will return a boolean
*/
public BooleanExpression(SQLStatement stmt, JavaTypeMapping mapping, String sql)
{
super(stmt, null, mapping);
st.clearStatement();
st.append(sql);
}
/**
* Constructor for a boolean expression for the specified mapping of the table.
* The boolean expression DOESN'T have closure using this constructor.
* @param stmt The statement
* @param table The table this mapping belongs to
* @param mapping the mapping associated to this expression
*/
public BooleanExpression(SQLStatement stmt, SQLTable table, JavaTypeMapping mapping)
{
super(stmt, table, mapping);
}
/**
* Constructor for a boolean expression for the specified mapping of the table.
* The boolean expression has closure using this constructor.
* @param stmt The statement
* @param mapping the mapping associated to this expression
*/
public BooleanExpression(SQLStatement stmt, JavaTypeMapping mapping)
{
super(stmt, null, mapping);
hasClosure = true;
}
/**
* Perform an operation <pre>op</pre> on expression <pre>expr1</pre>.
* The boolean expression has closure using this constructor.
* @param op operator
* @param expr1 operand
*/
public BooleanExpression(Expression.MonadicOperator op, SQLExpression expr1)
{
super(op, expr1);
hasClosure = true;
}
/**
* Perform an operation <pre>op</pre> between <pre>expr1</pre> and <pre>expr2</pre>.
* The boolean expression has closure using this constructor.
* @param expr1 the first expression
* @param op the operator between operands
* @param expr2 the second expression
*/
public BooleanExpression(SQLExpression expr1, Expression.DyadicOperator op, SQLExpression expr2)
{
super(expr1, op, expr2);
// Cater for some specific situations where we definitely want a boolean mapping and maybe the superclass didn't create the right one
if (op == Expression.OP_EQ || op == Expression.OP_GT || op == Expression.OP_GTEQ ||
op == Expression.OP_NOTEQ || op == Expression.OP_LT || op == Expression.OP_LTEQ)
{
mapping = stmt.getSQLExpressionFactory().getMappingForType(boolean.class, false);
}
else if (op == Expression.OP_IS || op == Expression.OP_ISNOT)
{
if (expr1 instanceof NullLiteral || expr2 instanceof NullLiteral)
{
// Comparison with null
mapping = stmt.getSQLExpressionFactory().getMappingForType(boolean.class, false);
}
}
hasClosure = true;
}
public boolean hasClosure()
{
return hasClosure;
}
public BooleanExpression and(SQLExpression expr)
{
if (expr instanceof BooleanLiteral)
{
return expr.and(this);
}
else if (expr instanceof BooleanExpression)
{
// Enforce closure. Maybe ought to refer to DatastoreAdapter.BOOLEAN_COMPARISON
BooleanExpression left = this;
BooleanExpression right = (BooleanExpression) expr;
if (!left.hasClosure())
{
left = left.eq(new BooleanLiteral(stmt, mapping, Boolean.TRUE));
}
if (!right.hasClosure())
{
right = right.eq(new BooleanLiteral(stmt, mapping, Boolean.TRUE));
}
if (stmt.getQueryGenerator() != null && stmt.getQueryGenerator().getCompilationComponent() == CompilationComponent.UPDATE)
{
// Special case : UPDATE clause AND should be replaced by boolean expression with "," separating the clauses
BooleanExpression boolExpr = new BooleanExpression(stmt, null, mapping);
boolExpr.st.append(left);
boolExpr.st.append(',');
boolExpr.st.append(right);
return boolExpr;
}
return new BooleanExpression(left, Expression.OP_AND, right);
}
else
{
return super.and(expr);
}
}
public BooleanExpression eor(SQLExpression expr)
{
if (expr instanceof BooleanLiteral)
{
return expr.eor(this);
}
else if (expr instanceof BooleanExpression)
{
if (stmt.getDatastoreAdapter().supportsOption(DatastoreAdapter.BOOLEAN_COMPARISON))
{
return new BooleanExpression(this, Expression.OP_NOTEQ, expr);
}
return and(expr.not()).ior(not().and(expr));
}
else
{
return super.eor(expr);
}
}
public BooleanExpression ior(SQLExpression expr)
{
if (expr instanceof BooleanLiteral)
{
return expr.ior(this);
}
else if (expr instanceof BooleanExpression)
{
// Enforce closure. Maybe ought to refer to DatastoreAdapter.BOOLEAN_COMPARISON
BooleanExpression left = this;
BooleanExpression right = (BooleanExpression) expr;
if (!left.hasClosure())
{
left = left.eq(new BooleanLiteral(stmt, mapping, Boolean.TRUE));
}
if (!right.hasClosure())
{
right = right.eq(new BooleanLiteral(stmt, mapping, Boolean.TRUE));
}
return new BooleanExpression(left, Expression.OP_OR, right);
}
else
{
return super.ior(expr);
}
}
public BooleanExpression not()
{
if (!hasClosure)
{
return new BooleanExpression(this, Expression.OP_EQ, new BooleanLiteral(stmt, mapping, Boolean.FALSE, null));
}
return new BooleanExpression(Expression.OP_NOT, this);
}
public BooleanExpression eq(SQLExpression expr)
{
if (isParameter() || expr.isParameter())
{
// Comparison with parameter, so just give boolean compare
return new BooleanExpression(this, Expression.OP_EQ, expr);
}
else if (expr instanceof BooleanLiteral || expr instanceof NullLiteral)
{
return expr.eq(this);
}
else if (expr instanceof BooleanExpression)
{
DatastoreMapping datastoreMapping = mapping.getDatastoreMapping(0);
if (datastoreMapping.isStringBased())
{
// Persisted using "Y", "N"
return new BooleanExpression(new CharacterExpression(stmt, table, mapping),
Expression.OP_EQ,
new CharacterExpression(stmt, expr.table, expr.mapping));
}
else if (datastoreMapping.isIntegerBased() || (datastoreMapping.isBitBased() &&
!stmt.getDatastoreAdapter().supportsOption(DatastoreAdapter.BIT_IS_REALLY_BOOLEAN)))
{
// Persisted using "1", "0"
return new BooleanExpression(new NumericExpression(stmt, table, mapping),
Expression.OP_EQ,
new NumericExpression(stmt, expr.table, expr.mapping));
}
else if (stmt.getDatastoreAdapter().supportsOption(DatastoreAdapter.BOOLEAN_COMPARISON))
{
return new BooleanExpression(this, Expression.OP_EQ, expr);
}
else
{
return and(expr).ior(not().and(expr.not()));
}
}
else
{
return super.eq(expr);
}
}
public BooleanExpression ne(SQLExpression expr)
{
if (isParameter() || expr.isParameter())
{
// Comparison with parameter, so just give boolean compare
return new BooleanExpression(this, Expression.OP_NOTEQ, expr);
}
else if (expr instanceof BooleanLiteral || expr instanceof NullLiteral)
{
return expr.ne(this);
}
else if (expr instanceof BooleanExpression)
{
DatastoreMapping datastoreMapping = mapping.getDatastoreMapping(0);
if (datastoreMapping.isStringBased())
{
// Persisted using "Y", "N"
return new BooleanExpression(new CharacterExpression(stmt, table, mapping),
Expression.OP_NOTEQ,
new CharacterExpression(stmt, expr.table, expr.mapping));
}
else if (datastoreMapping.isIntegerBased() || (datastoreMapping.isBitBased() &&
!stmt.getDatastoreAdapter().supportsOption(DatastoreAdapter.BIT_IS_REALLY_BOOLEAN)))
{
// Persisted using "1", "0"
return new BooleanExpression(new NumericExpression(stmt, table, mapping),
Expression.OP_NOTEQ,
new NumericExpression(stmt, expr.table, expr.mapping));
}
else if (stmt.getDatastoreAdapter().supportsOption(DatastoreAdapter.BOOLEAN_COMPARISON))
{
return new BooleanExpression(this, Expression.OP_NOTEQ, expr);
}
else
{
return and(expr.not()).ior(not().and(expr));
}
}
else
{
return super.ne(expr);
}
}
public BooleanExpression in(SQLExpression expr, boolean not)
{
DatastoreMapping datastoreMapping = mapping.getDatastoreMapping(0);
if (datastoreMapping.isStringBased())
{
return new BooleanExpression(new CharacterExpression(stmt, table, mapping),
(not ? Expression.OP_NOTIN : Expression.OP_IN), expr);
}
return new BooleanExpression(this, (not ? Expression.OP_NOTIN : Expression.OP_IN), expr);
}
public SQLExpression invoke(String methodName, List args)
{
return stmt.getRDBMSManager().getSQLExpressionFactory().invokeMethod(stmt, Boolean.class.getName(),
methodName, this, args);
}
public BooleanExpression neg()
{
return new BooleanExpression(Expression.OP_NEG, this);
}
} |
Java | public final class MessengerReceiveClientBuilder {
final String appSecret;
final String verifyToken;
boolean disableSignatureVerification;
AttachmentMessageEventHandler attachmentMessageEventHandler;
OptInEventHandler optInEventHandler;
EchoMessageEventHandler echoMessageEventHandler;
QuickReplyMessageEventHandler quickReplyMessageEventHandler;
TextMessageEventHandler textMessageEventHandler;
PostbackEventHandler postbackEventHandler;
AccountLinkingEventHandler accountLinkingEventHandler;
MessageReadEventHandler messageReadEventHandler;
MessageDeliveredEventHandler messageDeliveredEventHandler;
FallbackEventHandler fallbackEventHandler;
/**
* Constructs the builder. All parameter values are required. No {@link EventHandler} is set.
*
* @param appSecret the {@code Application Secret} of your {@code Facebook App} connected to your {@code Facebook Page}
* @param verifyToken the {@code Verification Token} that has been provided by you during the setup of the {@code Webhook}
*/
public MessengerReceiveClientBuilder(String appSecret, String verifyToken) {
PreConditions.notNullOrBlank(appSecret, "appSecret");
PreConditions.notNullOrBlank(verifyToken, "verifyToken");
this.appSecret = appSecret;
this.verifyToken = verifyToken;
}
/**
* Disables the signature verification. The signature verification ensures the integrity and origin of the payload.
*
* <p>
* <b>Disabling the signature verification is not recommended!</b>
* </p>
*
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder disableSignatureVerification() {
this.disableSignatureVerification = true;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link AttachmentMessageEvent}.
*
* @param attachmentMessageEventHandler an {@code AttachmentMessageEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onAttachmentMessageEvent(AttachmentMessageEventHandler attachmentMessageEventHandler) {
this.attachmentMessageEventHandler = attachmentMessageEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link OptInEvent}.
*
* @param optInEventHandler an {@code OptInEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onOptInEvent(OptInEventHandler optInEventHandler) {
this.optInEventHandler = optInEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link EchoMessageEvent}.
*
* @param echoMessageEventHandler an {@code EchoMessageEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onEchoMessageEvent(EchoMessageEventHandler echoMessageEventHandler) {
this.echoMessageEventHandler = echoMessageEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link QuickReplyMessageEvent}.
*
* @param quickReplyMessageEventHandler a {@code QuickReplyMessageEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onQuickReplyMessageEvent(QuickReplyMessageEventHandler quickReplyMessageEventHandler) {
this.quickReplyMessageEventHandler = quickReplyMessageEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link TextMessageEvent}.
*
* @param textMessageEventHandler a {@code TextMessageEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onTextMessageEvent(TextMessageEventHandler textMessageEventHandler) {
this.textMessageEventHandler = textMessageEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link PostbackEvent}.
*
* @param postbackEventHandler a {@code PostbackEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onPostbackEvent(PostbackEventHandler postbackEventHandler) {
this.postbackEventHandler = postbackEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link AccountLinkingEvent}.
*
* @param accountLinkingEventHandler an {@code AccountLinkingEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onAccountLinkingEvent(AccountLinkingEventHandler accountLinkingEventHandler) {
this.accountLinkingEventHandler = accountLinkingEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link MessageReadEvent}.
*
* @param messageReadEventHandler a {@code MessageReadEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onMessageReadEvent(MessageReadEventHandler messageReadEventHandler) {
this.messageReadEventHandler = messageReadEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link MessageDeliveredEvent}.
*
* @param messageDeliveredEventHandler a {@code MessageDeliveredEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder onMessageDeliveredEvent(MessageDeliveredEventHandler messageDeliveredEventHandler) {
this.messageDeliveredEventHandler = messageDeliveredEventHandler;
return this;
}
/**
* Sets the {@link EventHandler} responsible for handling the {@link FallbackEvent}.
*
* @param fallbackEventHandler a {@code FallbackEventHandler}
* @return the {@code MessengerReceiveClientBuilder}
*/
public MessengerReceiveClientBuilder fallbackEventHandler(FallbackEventHandler fallbackEventHandler) {
this.fallbackEventHandler = fallbackEventHandler;
return this;
}
/**
* Returns an instance of {@code MessengerReceiveClient} created from the fields set on this builder.
*
* @return a {@code MessengerReceiveClient}
*/
public MessengerReceiveClient build() {
return new MessengerReceiveClientImpl(this);
}
} |
Java | public class SmartMemberReader implements MemberReader {
private final SqlConstraintFactory sqlConstraintFactory =
SqlConstraintFactory.instance();
/** access to <code>source</code> must be synchronized(this) */
protected final MemberReader source;
protected final MemberCacheHelper cacheHelper;
protected List<RolapMember> rootMembers;
SmartMemberReader(MemberReader source) {
this.source = source;
this.cacheHelper = new MemberCacheHelper(source.getHierarchy());
if (!source.setCache(cacheHelper)) {
throw Util.newInternal(
"MemberSource (" + source + ", " + source.getClass()
+ ") does not support cache-writeback");
}
}
// implement MemberReader
public RolapCubeHierarchy getHierarchy() {
return source.getHierarchy();
}
public MemberCache getMemberCache() {
return cacheHelper;
}
// implement MemberSource
public boolean setCache(MemberCache cache) {
// we do not support cache writeback -- we must be masters of our
// own cache
return false;
}
public RolapMember substitute(RolapMember member) {
return member;
}
public RolapMember desubstitute(RolapMember member) {
return member;
}
public RolapMember getMemberByKey(
RolapCubeLevel level, List<Comparable> keyValues)
{
// Caching by key is not supported.
return source.getMemberByKey(level, keyValues);
}
// implement MemberReader
public List<RolapMember> getMembers() {
List<RolapMember> v = new ConcatenableList<RolapMember>();
// todo: optimize by walking to children for members we know about
for (RolapCubeLevel level : getHierarchy().getLevelList()) {
List<RolapMember> membersInLevel = getMembersInLevel(level);
v.addAll(membersInLevel);
}
return v;
}
public List<RolapMember> getRootMembers() {
if (rootMembers == null) {
rootMembers = source.getRootMembers();
}
return rootMembers;
}
public List<RolapMember> getMembersInLevel(
RolapCubeLevel level)
{
TupleConstraint constraint =
sqlConstraintFactory.getLevelMembersConstraint(null);
return getMembersInLevel(level, constraint);
}
public List<RolapMember> getMembersInLevel(
RolapCubeLevel level,
TupleConstraint constraint)
{
synchronized (cacheHelper) {
XmlaRequestContext context = XmlaRequestContext.getContext();
boolean isFromSmartBI = Objects.nonNull(context) && XmlaRequestContext.ClientType.SMARTBI.equals(context.clientType);
boolean pageFetchFlag = isFromSmartBI && context.queryPage != null && context.queryPage.inOnePage;
List<RolapMember> members =
cacheHelper.getLevelMembersFromCache(level, constraint);
if (members != null && !isFromSmartBI) {
return members;
}
members = source.getMembersInLevel(level, constraint);
if (!isFromSmartBI) {
cacheHelper.putLevelMembersInCache(level, constraint, members);
}
if (pageFetchFlag) {
if (context.queryPage.pageEnd <= members.size()) {
return members.subList(context.queryPage.pageStart, context.queryPage.pageEnd);
} else if (context.queryPage.queryStart < members.size()) {
return members.subList(context.queryPage.pageStart, members.size());
}
}
return members;
}
}
public int getLevelMemberCount(RolapCubeLevel level) {
// No need to cache the result: the caller saves the result by calling
// RolapLevel.setApproxRowCount
return source.getLevelMemberCount(level);
}
public void getMemberChildren(
RolapMember parentMember,
List<RolapMember> children)
{
MemberChildrenConstraint constraint =
sqlConstraintFactory.getMemberChildrenConstraint(null);
getMemberChildren(parentMember, children, constraint);
}
public void getMemberChildren(
RolapMember parentMember,
List<RolapMember> children,
MemberChildrenConstraint constraint)
{
List<RolapMember> parentMembers =
Collections.singletonList(parentMember);
getMemberChildren(parentMembers, children, constraint);
}
public void getMemberChildren(
List<RolapMember> parentMembers,
List<RolapMember> children)
{
MemberChildrenConstraint constraint =
sqlConstraintFactory.getMemberChildrenConstraint(null);
getMemberChildren(parentMembers, children, constraint);
}
public void getMemberChildren(
List<RolapMember> parentMembers,
List<RolapMember> children,
MemberChildrenConstraint constraint)
{
synchronized (cacheHelper) {
List<RolapMember> missed = new ArrayList<RolapMember>();
for (RolapMember parentMember : parentMembers) {
List<RolapMember> list =
cacheHelper.getChildrenFromCache(parentMember, constraint);
if (list == null) {
// the null member has no children
if (!parentMember.isNull()) {
missed.add(parentMember);
}
} else {
children.addAll(list);
}
}
if (missed.size() > 0) {
readMemberChildren(missed, children, constraint);
}
}
}
public RolapMember lookupMember(
List<Id.Segment> uniqueNameParts,
boolean failIfNotFound)
{
return RolapUtil.lookupMember(this, uniqueNameParts, failIfNotFound);
}
/**
* Reads the children of <code>member</code> into cache, and also into
* <code>result</code>.
*
* @param result Children are written here, in order
* @param members Members whose children to read
* @param constraint restricts the returned members if possible (optional
* optimization)
*/
protected void readMemberChildren(
List<RolapMember> members,
List<RolapMember> result,
MemberChildrenConstraint constraint)
{
if (false) {
// Pre-condition disabled. It makes sense to have the pre-
// condition, because lists of parent members are typically
// sorted by construction, and we should be able to exploit this
// when constructing the (significantly larger) set of children.
// But currently BasicQueryTest.testBasketAnalysis() fails this
// assert, and I haven't had time to figure out why.
// -- jhyde, 2004/6/10.
Util.assertPrecondition(isSorted(members), "isSorted(members)");
}
List<RolapMember> children = new ConcatenableList<RolapMember>();
source.getMemberChildren(members, children, constraint);
// Put them in a temporary hash table first. Register them later, when
// we know their size (hence their 'cost' to the cache pool).
Map<RolapMember, List<RolapMember>> tempMap =
new HashMap<RolapMember, List<RolapMember>>();
for (RolapMember member1 : members) {
tempMap.put(member1, Collections.<RolapMember>emptyList());
}
for (final RolapMember child : children) {
// todo: We could optimize here. If members.length is small, it's
// more efficient to drive from members, rather than hashing
// children.length times. We could also exploit the fact that the
// result is sorted by ordinal and therefore, unless the "members"
// contains members from different levels, children of the same
// member will be contiguous.
assert child != null : "child";
assert tempMap != null : "tempMap";
final RolapMember parentMember = child.getParentMember();
List<RolapMember> list = tempMap.get(parentMember);
if (list == null) {
// The list is null if, due to dropped constraints, we now
// have a children list of a member we didn't explicitly
// ask for it. Adding it to the cache would be viable, but
// let's ignore it.
continue;
} else if (list == Collections.EMPTY_LIST) {
list = new ArrayList<RolapMember>();
tempMap.put(parentMember, list);
}
((List)list).add(child);
((List)result).add(child);
}
synchronized (cacheHelper) {
for (Map.Entry<RolapMember, List<RolapMember>> entry
: tempMap.entrySet())
{
final RolapMember member = entry.getKey();
if (cacheHelper.getChildrenFromCache(member, constraint)
== null)
{
final List<RolapMember> list = entry.getValue();
cacheHelper.putChildren(member, constraint, list);
}
}
}
}
/**
* Returns true if every element of <code>members</code> is not null and is
* strictly less than the following element; false otherwise.
*/
public boolean isSorted(List<RolapMember> members) {
final int count = members.size();
if (count == 0) {
return true;
}
RolapMember m1 = members.get(0);
if (m1 == null) {
// Special case check for 0th element, just in case length == 1.
return false;
}
for (int i = 1; i < count; i++) {
RolapMember m0 = m1;
m1 = members.get(i);
if (m1 == null || compare(m0, m1, false) >= 0) {
return false;
}
}
return true;
}
public RolapMember getLeadMember(RolapMember member, int n) {
// uncertain if this method needs to be synchronized
synchronized (cacheHelper) {
if (n == 0 || member.isNull()) {
return member;
} else {
SiblingIterator iter = new SiblingIterator(this, member);
if (n > 0) {
RolapMember sibling = null;
while (n-- > 0) {
if (!iter.hasNext()) {
return member.getHierarchy().getNullMember();
}
sibling = iter.nextMember();
}
return sibling;
} else {
n = -n;
RolapMember sibling = null;
while (n-- > 0) {
if (!iter.hasPrevious()) {
return member.getHierarchy().getNullMember();
}
sibling = iter.previousMember();
}
return sibling;
}
}
}
}
public void getMemberRange(
RolapLevel level,
RolapMember startMember,
RolapMember endMember,
List<RolapMember> list)
{
assert startMember != null;
assert endMember != null;
assert startMember.getLevel() == endMember.getLevel();
if (compare(startMember, endMember, false) > 0) {
return;
}
list.add(startMember);
if (startMember.equals(endMember)) {
return;
}
SiblingIterator siblings = new SiblingIterator(this, startMember);
while (siblings.hasNext()) {
final RolapMember member = siblings.nextMember();
list.add(member);
if (member.equals(endMember)) {
return;
}
}
throw Util.newInternal(
"sibling iterator did not hit end point, start="
+ startMember + ", end=" + endMember);
}
public int getMemberCount() {
return source.getMemberCount();
}
public int compare(
RolapMember m1,
RolapMember m2,
boolean siblingsAreEqual)
{
if (m1.equals(m2)) {
return 0;
}
if (Util.equals(m1.getParentMember(), m2.getParentMember())) {
// including case where both parents are null
if (siblingsAreEqual) {
return 0;
} else if (m1.getParentMember() == null) {
// at this point we know that both parent members are null.
int pos1 = -1, pos2 = -1;
List<RolapMember> siblingList = getRootMembers();
for (int i = 0, n = siblingList.size(); i < n; i++) {
RolapMember child = siblingList.get(i);
if (child.equals(m1)) {
pos1 = i;
}
if (child.equals(m2)) {
pos2 = i;
}
}
if (pos1 == -1) {
throw Util.newInternal(m1 + " not found among siblings");
}
if (pos2 == -1) {
throw Util.newInternal(m2 + " not found among siblings");
}
Util.assertTrue(pos1 != pos2);
return pos1 < pos2 ? -1 : 1;
} else {
List<RolapMember> children = new ArrayList<RolapMember>();
getMemberChildren(m1.getParentMember(), children);
int pos1 = -1, pos2 = -1;
for (int i = 0, n = children.size(); i < n; i++) {
RolapMember child = children.get(i);
if (child.equals(m1)) {
pos1 = i;
}
if (child.equals(m2)) {
pos2 = i;
}
}
if (pos1 == -1) {
throw Util.newInternal(m1 + " not found among siblings");
}
if (pos2 == -1) {
throw Util.newInternal(m2 + " not found among siblings");
}
Util.assertTrue(pos1 != pos2);
return pos1 < pos2 ? -1 : 1;
}
}
int levelDepth1 = m1.getLevel().getDepth();
int levelDepth2 = m2.getLevel().getDepth();
if (levelDepth1 < levelDepth2) {
final int c = compare(m1, m2.getParentMember(), false);
return (c == 0) ? -1 : c;
} else if (levelDepth1 > levelDepth2) {
final int c = compare(m1.getParentMember(), m2, false);
return (c == 0) ? 1 : c;
} else {
return compare(m1.getParentMember(), m2.getParentMember(), false);
}
}
/**
* <code>SiblingIterator</code> helps traverse a hierarchy of members, by
* remembering the position at each level. Each SiblingIterator has a
* parent, to which it defers when the last child of the current member is
* reached.
*/
class SiblingIterator {
private final MemberReader reader;
private final SiblingIterator parentIterator;
private List<RolapMember> siblings;
private int position;
SiblingIterator(MemberReader reader, RolapMember member) {
this.reader = reader;
RolapMember parent = member.getParentMember();
List<RolapMember> siblingList;
if (parent == null) {
siblingList = reader.getRootMembers();
this.parentIterator = null;
} else {
siblingList = new ArrayList<RolapMember>();
reader.getMemberChildren(parent, siblingList);
this.parentIterator = new SiblingIterator(reader, parent);
}
this.siblings = siblingList;
this.position = -1;
for (int i = 0; i < this.siblings.size(); i++) {
if (siblings.get(i).equals(member)) {
this.position = i;
break;
}
}
if (this.position == -1) {
throw Util.newInternal(
"member " + member + " not found among its siblings");
}
}
boolean hasNext() {
return (this.position < this.siblings.size() - 1)
|| (parentIterator != null)
&& parentIterator.hasNext();
}
Object next() {
return nextMember();
}
RolapMember nextMember() {
if (++this.position >= this.siblings.size()) {
if (parentIterator == null) {
throw Util.newInternal("there is no next member");
}
RolapMember parent = parentIterator.nextMember();
List<RolapMember> siblingList = new ArrayList<RolapMember>();
reader.getMemberChildren(parent, siblingList);
this.siblings = siblingList;
this.position = 0;
}
return this.siblings.get(this.position);
}
boolean hasPrevious() {
return (this.position > 0)
|| (parentIterator != null)
&& parentIterator.hasPrevious();
}
Object previous() {
return previousMember();
}
RolapMember previousMember() {
if (--this.position < 0) {
if (parentIterator == null) {
throw Util.newInternal("there is no next member");
}
RolapMember parent = parentIterator.previousMember();
List<RolapMember> siblingList = new ArrayList<RolapMember>();
reader.getMemberChildren(parent, siblingList);
this.siblings = siblingList;
this.position = this.siblings.size() - 1;
}
return this.siblings.get(this.position);
}
}
public MemberBuilder getMemberBuilder() {
return source.getMemberBuilder();
}
public RolapMember getDefaultMember() {
RolapMember defaultMember = getHierarchy().getDefaultMember();
if (defaultMember != null) {
return defaultMember;
}
return getRootMembers().get(0);
}
public RolapMember getMemberParent(RolapMember member) {
// This method deals with ragged hierarchies but not access-controlled
// hierarchies - assume these have RestrictedMemberReader possibly
// wrapped in a SubstitutingMemberReader.
RolapMember parentMember = member.getParentMember();
// Skip over hidden parents.
while (parentMember != null && parentMember.isHidden()) {
parentMember = parentMember.getParentMember();
}
return parentMember;
}
} |
Java | class SiblingIterator {
private final MemberReader reader;
private final SiblingIterator parentIterator;
private List<RolapMember> siblings;
private int position;
SiblingIterator(MemberReader reader, RolapMember member) {
this.reader = reader;
RolapMember parent = member.getParentMember();
List<RolapMember> siblingList;
if (parent == null) {
siblingList = reader.getRootMembers();
this.parentIterator = null;
} else {
siblingList = new ArrayList<RolapMember>();
reader.getMemberChildren(parent, siblingList);
this.parentIterator = new SiblingIterator(reader, parent);
}
this.siblings = siblingList;
this.position = -1;
for (int i = 0; i < this.siblings.size(); i++) {
if (siblings.get(i).equals(member)) {
this.position = i;
break;
}
}
if (this.position == -1) {
throw Util.newInternal(
"member " + member + " not found among its siblings");
}
}
boolean hasNext() {
return (this.position < this.siblings.size() - 1)
|| (parentIterator != null)
&& parentIterator.hasNext();
}
Object next() {
return nextMember();
}
RolapMember nextMember() {
if (++this.position >= this.siblings.size()) {
if (parentIterator == null) {
throw Util.newInternal("there is no next member");
}
RolapMember parent = parentIterator.nextMember();
List<RolapMember> siblingList = new ArrayList<RolapMember>();
reader.getMemberChildren(parent, siblingList);
this.siblings = siblingList;
this.position = 0;
}
return this.siblings.get(this.position);
}
boolean hasPrevious() {
return (this.position > 0)
|| (parentIterator != null)
&& parentIterator.hasPrevious();
}
Object previous() {
return previousMember();
}
RolapMember previousMember() {
if (--this.position < 0) {
if (parentIterator == null) {
throw Util.newInternal("there is no next member");
}
RolapMember parent = parentIterator.previousMember();
List<RolapMember> siblingList = new ArrayList<RolapMember>();
reader.getMemberChildren(parent, siblingList);
this.siblings = siblingList;
this.position = this.siblings.size() - 1;
}
return this.siblings.get(this.position);
}
} |
Java | public class Constants
{
public Constants()
{
}
public static final String version = "1.101";
private static final Logger LOG = Logger.getLogger(Constants.class.getName());
} |
Java | public class RobotConsolePatternsListener implements IPatternMatchListener {
private TextConsole console;
private final RobotProject robotProject;
public RobotConsolePatternsListener(final RobotProject robotProject) {
this.robotProject = robotProject;
}
@Override
public void connect(final TextConsole console) {
this.console = console;
}
@Override
public void disconnect() {
this.console = null;
}
@Override
public void matchFound(final PatternMatchEvent event) {
try {
final String matchedLine = console.getDocument().get(event.getOffset(), event.getLength());
final PathWithOffset pathWithOffset = getPath(matchedLine);
final URI uri = getURI(pathWithOffset.path);
final int offset = event.getOffset() + pathWithOffset.offsetInLine;
final int length = pathWithOffset.path.length();
if (isValidUri(uri)) {
console.addHyperlink(new ExecutionWebsiteHyperlink(uri), offset, length);
} else {
final File file = new File(pathWithOffset.path);
console.addHyperlink(new ExecutionArtifactsHyperlink(robotProject.getProject(), file), offset, length);
}
} catch (final BadLocationException e) {
// fine, no hyperlinks then
}
}
private static URI getURI(final String path) {
try {
return new URI(path);
} catch (final URISyntaxException e) {
// fine, no link here
}
return null;
}
private static boolean isValidUri(final URI uri) {
final String scheme = uri == null ? null : uri.getScheme();
return scheme != null && (scheme.equals("http") || scheme.equals("https"));
}
private PathWithOffset getPath(final String matchedLine) {
if (matchedLine.startsWith("Debug:")) {
final String path = matchedLine.substring("Debug:".length()).trim();
final int offset = matchedLine.length() - path.length();
return new PathWithOffset(path, offset);
} else if (matchedLine.startsWith("Output:")) {
final String path = matchedLine.substring("Output:".length()).trim();
final int offset = matchedLine.length() - path.length();
return new PathWithOffset(path, offset);
} else if (matchedLine.startsWith("XUnit:")) {
final String path = matchedLine.substring("XUnit:".length()).trim();
final int offset = matchedLine.length() - path.length();
return new PathWithOffset(path, offset);
} else if (matchedLine.startsWith("Log:")) {
final String path = matchedLine.substring("Log:".length()).trim();
final int offset = matchedLine.length() - path.length();
return new PathWithOffset(path, offset);
} else if (matchedLine.startsWith("Report:")) {
final String path = matchedLine.substring("Report:".length()).trim();
final int offset = matchedLine.length() - path.length();
return new PathWithOffset(path, offset);
} else if (matchedLine.startsWith("Command:")) {
final String listenerArg = "--argumentfile ";
final int start = matchedLine.indexOf(listenerArg) + listenerArg.length();
final int end = matchedLine.indexOf(' ', start);
return new PathWithOffset(matchedLine.substring(start, end), start);
}
return null;
}
@Override
public String getPattern() {
return "(Debug|Output|XUnit|Log|Report|Command):\\s*(.*)";
}
@Override
public int getCompilerFlags() {
return 0;
}
@Override
public String getLineQualifier() {
return "(Debug|Output|XUnit|Log|Report|Command): ";
}
private static final class ExecutionArtifactsHyperlink implements IHyperlink {
private final IProject project;
private final File file;
private ExecutionArtifactsHyperlink(final IProject project, final File file) {
this.project = project;
this.file = file;
}
@Override
public void linkExited() {
// nothing to do
}
@Override
public void linkEntered() {
// nothing to do
}
@Override
public void linkActivated() {
final IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (!file.isFile() || !file.exists()) { // it could have been deleted in the meantime
final IStatus status = new Status(IStatus.ERROR, RedPlugin.PLUGIN_ID,
"The file " + file.getAbsolutePath() + " does not exist in the file system.");
ErrorDialog.openError(workbenchWindow.getShell(), "Missing file", "File does not exist", status);
return;
}
final IWorkspaceRoot root = project.getWorkspace().getRoot();
final RedWorkspace workspace = new RedWorkspace(root);
IFile wsFile = (IFile) workspace.forUri(file.toURI());
if (wsFile == null) {
wsFile = LibspecsFolder.get(project).getFile(file.getName());
try {
wsFile.createLink(file.toURI(), IResource.REPLACE | IResource.HIDDEN, null);
} catch (final CoreException e) {
throw new IllegalArgumentException("Unable to open file", e);
}
} else if (!wsFile.exists()) {
try {
refreshAllNeededResources(root, wsFile.getFullPath());
refreshFile(wsFile);
} catch (final CoreException e) {
final String message = "Unable to open editor for file: " + wsFile.getName();
ErrorDialog.openError(workbenchWindow.getShell(), "Error opening file", message,
new Status(IStatus.ERROR, RedPlugin.PLUGIN_ID, message, e));
}
}
try {
IDE.openEditor(workbenchWindow.getActivePage(), wsFile);
} catch (final PartInitException e) {
final String message = "Unable to open editor for file: " + wsFile.getName();
ErrorDialog.openError(workbenchWindow.getShell(), "Error opening file", message,
new Status(IStatus.ERROR, RedPlugin.PLUGIN_ID, message, e));
}
}
private IFile refreshAllNeededResources(final IWorkspaceRoot root, final IPath wsRelative)
throws CoreException {
IPath path = wsRelative;
final List<String> removed = newArrayList();
while (root.findMember(path) == null) {
removed.add(0, path.lastSegment());
path = path.removeLastSegments(1);
}
for (final String segment : removed) {
root.findMember(path).refreshLocal(IResource.DEPTH_ONE, null);
path = path.append(segment);
}
return (IFile) root.findMember(wsRelative);
}
private void refreshFile(final IFile wsFile) throws CoreException {
if (!wsFile.isSynchronized(IResource.DEPTH_ZERO)) {
wsFile.refreshLocal(IResource.DEPTH_ZERO, null);
}
}
}
private static final class ExecutionWebsiteHyperlink implements IHyperlink {
private final URI link;
private ExecutionWebsiteHyperlink(final URI link) {
this.link = link;
}
@Override
public void linkExited() {
// nothing to do
}
@Override
public void linkEntered() {
// nothing to do
}
@Override
public void linkActivated() {
final IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
try {
final IWebBrowser browser = support.createBrowser("default");
browser.openURL(link.toURL());
} catch (PartInitException | MalformedURLException e) {
final IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
final String message = "Unable to open link: " + link.toString();
ErrorDialog.openError(workbenchWindow.getShell(), "Error opening link", message,
new Status(IStatus.ERROR, RedPlugin.PLUGIN_ID, message, e));
}
}
}
private static class PathWithOffset {
private final String path;
private final int offsetInLine;
public PathWithOffset(final String path, final int offsetInLine) {
this.path = path;
this.offsetInLine = offsetInLine;
}
}
} |
Java | public class SearchOntology extends BeanOntology {
/**
*
*/
private static final long serialVersionUID = -1829196889268218770L;
private SearchOntology() {
super("SearchOntology");
try {
String searchItemPackage = SearchItem.class.getPackage().getName();
String boolPackage = BooleanValue.class.getPackage().getName();
add(SearchSolution.class);
add(ExecuteParameters.class);
add(GetParameters.class);
add(searchItemPackage);
add(boolPackage);
add(SearchItem.class);
add(Evaluation.class);
} catch (Exception e) {
ConsoleLogger.logThrowable("Unexpected error occured:", e);
}
}
static SearchOntology theInstance = new SearchOntology();
public static Ontology getInstance() {
return theInstance;
}
} |
Java | public class ConsumerDeserializerTest {
private static final String VALID_CONFIGS = "\"configs\": {"
+ "\"group.id\":\"group0\","
+ "\"bootstrap.servers\":\"localhost:9092\","
+ "\"key.deserializer\":\"org.apache.kafka.common.serialization.StringDeserializer\","
+ "\"value.deserializer\":\"org.apache.kafka.common.serialization.StringDeserializer\""
+ "}";
private static final String VALID_TOPICS = "\"topics\":[\"test\"]";
/*
* {
* "configs": {
* "group.id":"group0",
* "bootstrap.servers":"localhost:9092",
* "key.deserializer":"org.apache.kafka.common.serialization.StringDeserializer",
* "value.deserializer":"org.apache.kafka.common.serialization.StringDeserializer"
* },
* "topics":["test"]
* }
*/
private static final String CONSUMER_JSON_VALID = makeJsonObject(VALID_CONFIGS, VALID_TOPICS);
private static final String CONSUMER_JSON_MALFORMED = "{" + VALID_CONFIGS + VALID_TOPICS + "}";
private static final String CONSUMER_JSON_NO_KEY_DESERIALIZER = makeJsonObject(
"\"configs\": {\"group.id\":\"group0\",\"bootstrap.servers\":\"localhost:9092\","
+ "\"value.deserializer\":\"org.apache.kafka.common.serialization.StringDeserializer\"}", VALID_TOPICS);
private static final String CONSUMER_JSON_NO_VALUE_DESERIALIZER = makeJsonObject(
"\"configs\": {\"group.id\":\"group0\",\"bootstrap.servers\":\"localhost:9092\","
+ "\"key.deserializer\":\"org.apache.kafka.common.serialization.StringDeserializer\"}", VALID_TOPICS);
private static final String CONSUMER_JSON_NO_BOOTSTRAP_SERVER = makeJsonObject(
"\"configs\": {\"group.id\":\"group0\","
+ "\"key.deserializer\":\"org.apache.kafka.common.serialization.StringDeserializer\","
+ "\"value.deserializer\":\"org.apache.kafka.common.serialization.StringDeserializer\"}", VALID_TOPICS);
private static final String CONSUMER_JSON_NO_CONFIG = makeJsonObject(VALID_TOPICS);
private static final String CONSUMER_JSON_NO_TOPICS = makeJsonObject(VALID_CONFIGS);
private static final String CONSUMER_JSON_CONFIGS_NOT_OBJECT = makeJsonObject("\"configs\": true", VALID_TOPICS);
private static final String CONSUMER_JSON_CONFIGS_NULL = makeJsonObject("\"configs\": null", VALID_TOPICS);
private static final String CONSUMER_JSON_TOPICS_NOT_LIST = makeJsonObject(VALID_CONFIGS, "\"topics\":\"test\"");
private static final String CONSUMER_JSON_TOPICS_NULL = makeJsonObject(VALID_CONFIGS, "\"topics\":null");
private static final ObjectMapper OBJECT_MAPPER = ObjectMapperFactory.createInstance();
@BeforeClass
public static void setUpClass() throws IOException {
Files.createDirectories(new File("./target/tmp/filter/ConsumerDeserializer").toPath());
final SimpleModule module = new SimpleModule("KafkaConsumer");
module.addDeserializer(Consumer.class, new ConsumerDeserializer<>());
OBJECT_MAPPER.registerModule(module);
}
/* --- Success --- */
@Test
public void testDeserializeConsumerSuccess() throws IOException {
final Consumer<String, String> consumer = createConsumerFromJSON(CONSUMER_JSON_VALID);
Assert.assertEquals(Sets.newHashSet("test"), consumer.subscription());
}
/* --- Invalid JSON --- */
@Test(expected = JsonParseException.class)
public void testDeserializeConsumerMalformedJson() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_MALFORMED);
}
/* --- Not JSON Object --- */
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerNotJsonObjectNumber() throws IOException {
createConsumerFromJSON("1000");
}
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerNotJsonObjectList() throws IOException {
createConsumerFromJSON("[10, 10]");
}
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerNotJsonObjectBoolean() throws IOException {
createConsumerFromJSON("true");
}
/* --- Valid JSON Object but Wrong Field Types--- */
@Test(expected = JsonMappingException.class)
public void testDeserializeConsumerTopicsNotList() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_TOPICS_NOT_LIST);
}
@Test(expected = JsonMappingException.class)
public void testDeserializeConsumerConfigsNotObject() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_CONFIGS_NOT_OBJECT);
}
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerTopicsNotListNull() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_TOPICS_NULL);
}
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerConfigsNotObjectNull() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_CONFIGS_NULL);
}
/* --- Valid JSON Object but Missing Fields --- */
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerMissingConfigsField() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_NO_CONFIG);
}
@Test(expected = MismatchedInputException.class)
public void testDeserializeConsumerMissingTopicsField() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_NO_TOPICS);
}
/* --- Valid JSON but Configs Missing Needed Fields --- */
@Test(expected = JsonMappingException.class)
public void testDeserializeConsumerMissingKeyDeserializer() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_NO_KEY_DESERIALIZER);
}
@Test(expected = JsonMappingException.class)
public void testDeserializeConsumerMissingValueDeserializer() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_NO_VALUE_DESERIALIZER);
}
@Test(expected = JsonMappingException.class)
public void testDeserializeConsumerMissingBootstrapServer() throws IOException {
createConsumerFromJSON(CONSUMER_JSON_NO_BOOTSTRAP_SERVER);
}
private static Consumer<String, String> createConsumerFromJSON(final String jsonString)
throws IOException {
return OBJECT_MAPPER.readValue(jsonString, new TypeReference<Consumer<String, String>>() {});
}
private static String makeJsonObject(final String... fields) {
final StringBuilder jsonObject = new StringBuilder("{");
for (int i = 0; i < fields.length; i++) {
if (i != 0) {
jsonObject.append(",");
}
jsonObject.append(fields[i]);
}
jsonObject.append("}");
return jsonObject.toString();
}
} |
Java | public class IncludeAwareEventReaderTest {
XMLInputFactory xmlInputFactory;
private DocumentBuilderFactory documentBuilderFactory;
private TransformerFactory transformerFactory;
@Before
public void setup() {
xmlInputFactory = XMLInputFactory.newFactory();
documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setXIncludeAware(true);
transformerFactory = TransformerFactory.newInstance();
}
/**
* Tests parsing a simple XML file with no includes.
*
* @throws ParserConfigurationException if there is a problem using the DOM parser
* @throws SAXException if there is a problem parsing using the DOM parser
* @throws IOException if the XML file cannot be found
* @throws TransformerException if the XML file, after includes, cannot be written
* @throws XMLStreamException if there is a problem parsing using the StAX parser
*/
@Test
public void testNoIncludes() throws ParserConfigurationException, SAXException, IOException,
TransformerException, XMLStreamException {
checkSameEvents(new File("src/test/resources/no-include.xml"));
}
/**
* Tests parsing an XML file with an include from the same directory.
*
* @throws ParserConfigurationException if there is a problem using the DOM parser
* @throws SAXException if there is a problem parsing using the DOM parser
* @throws IOException if the XML file cannot be found
* @throws TransformerException if the XML file, after includes, cannot be written
* @throws XMLStreamException if there is a problem parsing using the StAX parser
*/
@Test
public void testSimpleInclude() throws ParserConfigurationException, SAXException, IOException,
TransformerException, XMLStreamException {
checkSameEvents(new File("src/test/resources/simple-include.xml"));
}
/**
* Tests parsing an XML file with an include from a subdirectory.
*
* @throws ParserConfigurationException if there is a problem using the DOM parser
* @throws SAXException if there is a problem parsing using the DOM parser
* @throws IOException if the XML file cannot be found
* @throws TransformerException if the XML file, after includes, cannot be written
* @throws XMLStreamException if there is a problem parsing using the StAX parser
*/
@Test
public void testSubdirInclude() throws ParserConfigurationException, SAXException, IOException,
TransformerException, XMLStreamException {
checkSameEvents(new File("src/test/resources/subdir-include.xml"));
}
/**
* Tests parsing an XML file with multiple levels of includes.
*
* @throws ParserConfigurationException if there is a problem using the DOM parser
* @throws SAXException if there is a problem parsing using the DOM parser
* @throws IOException if the XML file cannot be found
* @throws TransformerException if the XML file, after includes, cannot be written
* @throws XMLStreamException if there is a problem parsing using the StAX parser
*/
@Test
public void testNestedInclude() throws ParserConfigurationException, SAXException, IOException,
TransformerException, XMLStreamException {
checkSameEvents(new File("src/test/resources/nested-include.xml"));
}
/**
* Tests that closing an include-aware reader closes the underlying
* event readers for all included files.
*
* @throws ParserConfigurationException if there is a problem using the DOM parser
* @throws SAXException if there is a problem parsing using the DOM parser
* @throws IOException if the XML file cannot be found
* @throws TransformerException if the XML file, after includes, cannot be written
* @throws XMLStreamException if there is a problem parsing using the StAX parser
*/
@Test
public void testCloseReader() throws ParserConfigurationException, SAXException, IOException,
TransformerException, XMLStreamException {
IncludeAwareEventReader reader = new IncludeAwareEventReader(new File("src/test/resources/direct-include.xml").toURI(), xmlInputFactory);
reader.nextTag(); // Start tag in main file.
reader.nextTag(); // Start tag in included file.
reader.close();
assertTrue(reader.isClosed());
}
/**
* Tests that attempting to parse a nonexistent file
* generates a parse exception.
*
* @throws XMLStreamException if there is an error parsing the file
*/
@Test(expected = XMLStreamException.class)
public void testParseNonexistentFile() throws XMLStreamException {
readEventsFromFile(new IncludeAwareEventReader(new File("src/test/resources/nonexistent.xml").toURI(), xmlInputFactory));
}
/**
* Tests that an <xi:include> for a nonexistent file
* generates a parse exception.
*
* @throws XMLStreamException if there is an error parsing the file
*/
@Test(expected = XMLStreamException.class)
public void testIncludeNonexistentFile() throws XMLStreamException {
readEventsFromFile(new IncludeAwareEventReader(new File("src/test/resources/include-nonexistent-file.xml").toURI(), xmlInputFactory));
}
/**
* Tests that an <xi:include> without an href attribute
* generates a parse exception.
*
* @throws XMLStreamException if there is an error parsing the file
*/
@Test(expected = XMLStreamException.class)
public void testIncludeWithoutHref() throws XMLStreamException {
readEventsFromFile(new IncludeAwareEventReader(new File("src/test/resources/no-href-include.xml").toURI(), xmlInputFactory));
}
/**
* Tests that an <xi:include> with a parsing type other than
* XML generates a parse exception.
*
* @throws XMLStreamException if there is an error parsing the file
*/
@Test(expected = XMLStreamException.class)
public void testIncludeWithNonXMLParse() throws XMLStreamException {
readEventsFromFile(new IncludeAwareEventReader(new File("src/test/resources/non-xml-include.xml").toURI(), xmlInputFactory));
}
/**
* Tests that a file generates the same events when parsed with a StAX
* parser both when preprocessing the <xi:include> instructions
* using a DOM transformer and when parsed directly using an include-aware
* event reader.
*
* @param f the file to test
* @throws ParserConfigurationException if there is a problem using the DOM parser
* @throws SAXException if there is a problem parsing using the DOM parser
* @throws IOException if the XML file cannot be found
* @throws TransformerException if the XML file, after includes, cannot be written
* @throws XMLStreamException if there is a problem parsing using the StAX parser
*/
private void checkSameEvents(File f) throws ParserConfigurationException, SAXException, IOException,
TransformerException, XMLStreamException {
// Read the file using the DOM parser, processing any <code>xi:include</code>
// elements.
File tempFile = File.createTempFile(this.getClass().getSimpleName(), "xml");
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
assertTrue(builder.isXIncludeAware());
Document doc = builder.parse(f);
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(tempFile));
transformer.transform(source, result);
// Now read both files and check that the event streams are the same, except for
// ignorable whitespace.
List<XMLEvent> stream1 = readEventsFromFile(new IncludeAwareEventReader(f.toURI(), xmlInputFactory));
List<XMLEvent> stream2 = readEventsFromFile(xmlInputFactory.createXMLEventReader(new FileInputStream(tempFile)));
checkSameEvents(stream2, stream1);
}
/**
* Checks that two lists of parsing events are the same, by checking the event types.
*
* @param stream1 the first event list
* @param stream2 the second event list
*/
private void checkSameEvents(List<XMLEvent> stream1, List<XMLEvent> stream2) {
assertEquals(stream1.size(), stream2.size());
Iterator<XMLEvent> it1 = stream1.iterator();
Iterator<XMLEvent> it2 = stream2.iterator();
while (it1.hasNext() && it2.hasNext()) {
assertEquals(it1.next().getEventType(), it2.next().getEventType());
}
}
/**
* Gets the list of parsing events that occur when parsing an XML file
* using a StAX reader. Ignores processing instructions and character
* events that include only whitespace.
*
* @param reader the event reader
* @return a list of events
* @throws XMLStreamException if there is an error parsing the XML file
*/
private List<XMLEvent> readEventsFromFile(XMLEventReader reader) throws XMLStreamException {
List<XMLEvent> events = new ArrayList<>();
while (reader.peek() != null) {
XMLEvent event = reader.nextEvent();
if (event == null) {
break;
} else if (event.isProcessingInstruction()) {
// Ignore
} else if (event.isCharacters() && event.asCharacters().isWhiteSpace()) {
// Ignore
} else {
events.add(reader.nextEvent());
// Note that we don't read the element text. We are just looking
// at the start/end element and document events.
}
}
return events;
}
} |
Java | class HexDump {
private static final String CODE = "0123456789abcdef";
public static String toHex(byte[] buf) {
return toHex(buf, 0, buf.length);
}
public static String toHex(byte[] buf, int start, int len) {
StringBuilder r = new StringBuilder(len * 2);
boolean inText = false;
for (int i = 0; i < len; i++) {
byte b = buf[start + i];
if (b >= 0x20 && b <= 0x7e) {
if (!inText) {
inText = true;
r.append('\'');
}
r.append((char) b);
} else {
if (inText) {
r.append("' ");
inText = false;
}
r.append("0x");
r.append(CODE.charAt((b >> 4) & 15));
r.append(CODE.charAt(b & 15));
if (i < len - 1) {
if (b == 10) {
r.append('\n');
} else {
r.append(' ');
}
}
}
}
if (inText) {
r.append('\'');
}
return r.toString();
}
} |
Java | public class YSlow {
private static YSlow INSTANCE = null;
private static Logger logger = Logger.getLogger(YSlow.class.getName());
/***********************************************************************
*
***********************************************************************/
private YSlow(){
//ExecutionContextPool.initializeExecutors(10);
}
/***********************************************************************
*
***********************************************************************/
public static YSlow instance(){
if(INSTANCE == null){
INSTANCE = new YSlow();
}
return INSTANCE;
}
/***********************************************************************
*
***********************************************************************/
public String analyzeHarString(String harString){
CFWLog log = new CFWLog(logger);
log.start();
ExecutionContext context = ExecutionContextPool.lockContext();
//----------------------------------------------
// Execute the Java FX Application.
// It will set the Result on the singelton instance
Platform.runLater(new Runnable(){
@Override
public void run() {
YSlowExecutorJavaFX.analyzeHARString(context, harString);
}
});
//----------------------------------------------
//wait for result, max 50 seconds
for(int i = 0; !context.isResultUpdated() && i < 100; i++){
try {
System.out.println("wait");
Thread.sleep(500);
} catch (InterruptedException e) {
log.severe("Thread was interrupted.", e);
}
}
String result = context.getResult();
ExecutionContextPool.releaseContext(context);
log.end();
return result;
}
} |
Java | public class MapCqlLibraryProviderFactory {
private final ZipStreamProcessor zipProcessor;
public MapCqlLibraryProviderFactory() {
this(new ZipStreamProcessor());
}
public MapCqlLibraryProviderFactory(ZipStreamProcessor zipProcessor) {
this.zipProcessor = zipProcessor;
}
public CqlLibraryProvider fromDirectory(Path directory, String... searchPaths) throws IOException {
Map<CqlLibraryDescriptor, CqlLibrary> map = new HashMap<>();
try (Stream<Path> stream = Files.walk(directory, FileVisitOption.FOLLOW_LINKS)) {
map = stream
.filter(x -> PathHelper.isInSearchPaths(directory, x, searchPaths))
.filter(x -> CqlLibraryHelpers.isFileReadable(x.toString()))
.map(this::toCqlLibrary)
.collect(Collectors.toMap(CqlLibrary::getDescriptor, Function.identity()));
}
return new MapCqlLibraryProvider(map);
}
public CqlLibraryProvider fromZipFile(Path zipFile, String... searchPaths) throws IOException {
try(InputStream is = new FileInputStream(zipFile.toFile())) {
ZipInputStream zis = new ZipInputStream(is);
return fromZipStream(zis, searchPaths);
}
}
public CqlLibraryProvider fromZipStream(ZipInputStream zipStream, String... searchPaths) throws IOException {
Map<CqlLibraryDescriptor, CqlLibrary> map = new HashMap<>();
zipProcessor.processZip(zipStream, searchPaths, (filename, content) -> {
if (CqlLibraryHelpers.isFileReadable(filename)) {
CqlLibraryDescriptor descriptor = CqlLibraryHelpers.filenameToLibraryDescriptor(filename);
CqlLibrary cqlLibrary = new CqlLibrary()
.setDescriptor(descriptor)
.setContent(content);
map.put(descriptor, cqlLibrary);
}
});
return new MapCqlLibraryProvider(map);
}
private CqlLibrary toCqlLibrary(Path path) {
CqlLibraryDescriptor descriptor = CqlLibraryHelpers.filenameToLibraryDescriptor(path.toString());
String content = readFile(path);
return new CqlLibrary()
.setContent(content)
.setDescriptor(descriptor);
}
private String readFile(Path path) {
try {
return IOUtils.toString(path.toUri(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} |
Java | public final class DefaultInMemoryTracer extends AbstractInMemoryTracer {
private static final Logger logger = LoggerFactory.getLogger(DefaultInMemoryTracer.class);
private final InMemoryScopeManager scopeManager;
private final BiFunction<String, Boolean, Boolean> sampler;
private final InMemorySpanEventListener listeners;
private final int maxTagSize;
private final boolean persistLogs;
private final boolean use128BitTraceId;
/**
* Builders for {@link DefaultInMemoryTracer}.
*/
public static final class Builder {
private final InMemoryScopeManager scopeManager;
private final CopyOnWriteInMemorySpanEventListenerSet listeners = new CopyOnWriteInMemorySpanEventListenerSet();
private BiFunction<String, Boolean, Boolean> sampler = SamplingStrategies.sampleUnlessFalse();
private int maxTagSize = 16;
private boolean persistLogs;
private boolean use128BitTraceId;
/**
* Constructs a builder for an {@link DefaultInMemoryTracer}.
*
* @param scopeManager a {@link InMemoryScopeManager}.
*/
public Builder(InMemoryScopeManager scopeManager) {
this.scopeManager = requireNonNull(scopeManager);
}
/**
* Sets the sampler.
*
* @param sampler policy which takes a traceId and returns whether the given trace should be sampled
* @return this
*/
public Builder withSampler(Predicate<String> sampler) {
requireNonNull(sampler);
withSampler((traceId, requested) -> requested != null ? requested : sampler.test(traceId));
return this;
}
/**
* Sets the sampler.
*
* @param sampler policy which takes a traceId and the sampling flag specified in carrier (optional,
* could be {@code null}), and returns whether the given trace should be sampled.
* @return this
*/
public Builder withSampler(BiFunction<String, Boolean, Boolean> sampler) {
this.sampler = requireNonNull(sampler);
return this;
}
/**
* Add a trace event listener.
*
* @param listener listener to add
* @return this
*/
public Builder addListener(InMemorySpanEventListener listener) {
listeners.add(requireNonNull(listener));
return this;
}
/**
* Sets the maximum number of tags.
*
* @param maxTagSize maximum number of tags
* @return this
*/
public Builder withMaxTagSize(int maxTagSize) {
if (maxTagSize < 0) {
throw new IllegalArgumentException("maxTagSize must be >= 0");
}
this.maxTagSize = maxTagSize;
return this;
}
/**
* Sets whether logs are persisted in the span object. This is necessary when using using
* listeners which sends the span to a backend on span finish.
*
* @param persistLogs whether to persist logs in the span object. Defaults to false.
* @return this
*/
public Builder persistLogs(boolean persistLogs) {
this.persistLogs = persistLogs;
return this;
}
/**
* Sets whether to use 128-bit trace IDs.
*
* @param use128BitTraceId whether to use 128-bit trace IDs.
* @return this
*/
public Builder use128BitTraceId(boolean use128BitTraceId) {
this.use128BitTraceId = use128BitTraceId;
return this;
}
/**
* Builds the {@link DefaultInMemoryTracer}.
*
* @return tracer
*/
public DefaultInMemoryTracer build() {
return new DefaultInMemoryTracer(scopeManager, sampler, listeners, maxTagSize, persistLogs,
use128BitTraceId);
}
}
private DefaultInMemoryTracer(
InMemoryScopeManager scopeManager, BiFunction<String, Boolean, Boolean> sampler,
InMemorySpanEventListener listeners, int maxTagSize, boolean persistLogs,
boolean use128BitTraceId) {
this.scopeManager = scopeManager;
this.sampler = sampler;
this.listeners = listeners;
this.maxTagSize = maxTagSize;
this.persistLogs = persistLogs;
this.use128BitTraceId = use128BitTraceId;
}
@Override
public InMemoryScopeManager scopeManager() {
return scopeManager;
}
@Nullable
@Override
public InMemorySpan activeSpan() {
InMemoryScope scope = this.scopeManager.active();
return scope == null ? null : scope.span();
}
@Override
public InMemorySpanBuilder buildSpan(final String operationName) {
return new DefaultInMemorySpanBuilder(operationName);
}
@Override
protected InMemorySpanContext newSpanContext(final InMemoryTraceState state) {
return new DefaultInMemorySpanContext(state, isSampled(state.traceIdHex(), state.isSampled()));
}
private final class DefaultInMemorySpanBuilder extends AbstractInMemorySpanBuilder {
DefaultInMemorySpanBuilder(String operationName) {
super(operationName, DefaultInMemoryTracer.this.maxTagSize);
}
@Override
protected InMemorySpan createSpan(
@Nullable String kind, String operationName, List<InMemoryReference> references,
Map<String, Object> tags, int maxTagSize, boolean ignoreActiveSpan, long startTimestampMicros) {
InMemorySpanContext maybeParent = parent();
if (maybeParent == null && !ignoreActiveSpan) {
// Try to infer the parent based upon the ScopeManager's active Scope.
InMemoryScope activeScope = scopeManager().active();
if (activeScope != null) {
maybeParent = activeScope.span().context();
}
}
final String traceIdHex;
final String spanIdHex;
final String parentSpanIdHex;
final boolean sampled;
if (maybeParent != null) {
traceIdHex = maybeParent.traceState().traceIdHex();
spanIdHex = nextId();
parentSpanIdHex = maybeParent.traceState().spanIdHex();
sampled = maybeParent.isSampled();
} else {
spanIdHex = nextId();
traceIdHex = use128BitTraceId ? nextId() + spanIdHex : spanIdHex;
parentSpanIdHex = null;
sampled = isSampled(traceIdHex, null);
}
if (sampled) {
SampledInMemorySpan span = new SampledInMemorySpan(operationName, references,
traceIdHex, spanIdHex, parentSpanIdHex, tags, maxTagSize, startTimestampMicros,
listeners, persistLogs);
span.start();
return span;
} else {
return new UnsampledInMemorySpan(operationName, references, traceIdHex, spanIdHex, parentSpanIdHex);
}
}
@Override
public InMemoryScope startActive(final boolean finishSpanOnClose) {
return scopeManager().activate(start(), finishSpanOnClose);
}
}
private static String nextId() {
// We should be careful to select a randomly generated ID. If we choose to use a counter, and another
// application also chooses a counter there is a chance we will be synchronized and have a higher probability of
// overlapping IDs.
return hexBytesOfLong(ThreadLocalRandom.current().nextLong());
}
private boolean isSampled(String traceId, @Nullable Boolean requestedByCarrier) {
try {
return sampler.apply(traceId, requestedByCarrier);
} catch (Throwable t) {
logger.warn("Exception from sampler={}, default to not sampling", sampler, t);
return false; // play safe, default to not sampling
}
}
} |
Java | public class IntegrationTestConstants {
// DataServer variations.
public static final String NETTY_DATA_SERVER = "tachyon.worker.netty.NettyDataServer";
public static final String NIO_DATA_SERVER = "tachyon.worker.nio.NIODataServer";
// Remote block reader variations.
public static final String TCP_BLOCK_READER = "tachyon.client.tcp.TCPRemoteBlockReader";
public static final String NETTY_BLOCK_READER = "tachyon.client.netty.NettyRemoteBlockReader";
// Netty transfer types.
public static final String MAPPED_TRANSFER = "MAPPED";
public static final String FILE_CHANNEL_TRANSFER = "TRANSFER";
public static final String UNUSED_TRANSFER = "UNUSED";
} |
Java | public final class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
public static AkkaServerless createAkkaServerless() {
// The AkkaServerlessFactory automatically registers any generated Actions, Views or Entities,
// and is kept up-to-date with any changes in your protobuf definitions.
// If you prefer, you may remove this and manually register these components in a
// `new AkkaServerless()` instance.
return AkkaServerlessFactory.withComponents(
EventSourcedConfiguredEntity::new,
EventSourcedTckModelEntity::new,
EventSourcedTwoEntity::new,
ValueEntityConfiguredEntity::new,
ValueEntityTckModelEntity::new,
ValueEntityTwoEntity::new,
ViewTckSourceEntity::new,
ActionTckModelImpl::new,
ActionTwoImpl::new,
ViewTckModelImpl::new);
}
public static void main(String[] args) throws Exception {
LOG.info("starting the Akka Serverless service");
createAkkaServerless().start();
}
} |
Java | @RunWith(RobolectricTestRunner.class)
@Config(sdk = {VERSION_CODES.P}, manifest = Config.NONE)
public final class DfuUtilTest {
private String dfuDirectory;
@Before
public void setup() {
PrintLogger.initialize(ApplicationProvider.getApplicationContext());
dfuDirectory = ApplicationProvider.getApplicationContext().getFilesDir().getAbsolutePath();
}
@Test
public void crc16_successful() {
// Assign
byte[] message = "Hello".getBytes();
// Act
int response = DfuUtil.crc16(message, message.length);
// Assert
assertThat(response).isEqualTo(/* expected= */52182);
}
@Test
public void crc16_zero() {
// Assign
byte[] message = "".getBytes();
// Act
int response = DfuUtil.crc16(message, message.length);
// Assert
assertThat(response).isEqualTo(/* expected= */0);
}
@Test
public void getFileSize_fileNotExists() {
// Act
long response = DfuUtil.getFileSize(dfuDirectory, getDfuInfo());
// Assert
assertThat(response).isEqualTo(/* expected= */0);
}
@Test
public void getFileSize() throws IOException {
// Assign
String fileText = "Hello";
DFUInfo dfuInfo = getDfuInfo();
createFile(dfuInfo, fileText);
// Act
long response = DfuUtil.getFileSize(dfuDirectory, dfuInfo);
// Assert
assertThat(response).isEqualTo(fileText.length());
}
@Test
public void getAbsolutePath() throws IOException {
// Assign
String fileText = "Hello";
DFUInfo dfuInfo = getDfuInfo();
createFile(dfuInfo, fileText);
// Act
String response = DfuUtil.getFirmwareFilePath(dfuDirectory, dfuInfo);
// Assert
assertThat(response).isEqualTo(
dfuDirectory + File.separator + dfuInfo.vendorId() + SEPARATOR + dfuInfo.productId()
+ SEPARATOR + dfuInfo.moduleId() + SEPARATOR + dfuInfo.version().toString());
}
private void createFile(DFUInfo dfuInfo, String text) throws IOException {
File file = new File(DfuUtil.getFirmwareFilePath(dfuDirectory, dfuInfo));
file.createNewFile();
FileWriter myWriter = new FileWriter(file);
myWriter.write(text);
myWriter.close();
}
private static DFUInfo getDfuInfo() {
String version = "000006000";
String dfuStatus = "optional";
URI downloadUrl = null;
try {
downloadUrl = new URI("https://storage.googleapis.com/");
} catch (URISyntaxException e) {
e.printStackTrace();
}
String vendorId = "42-f9-a1-e3";
String productId = "73-d0-58-c3";
String moduleId = "a9-46-5b-d3";
return DFUInfo.create(version, dfuStatus, downloadUrl, vendorId, productId, moduleId);
}
@Test
public void givenFileToInputStreamToFile_whenCreateNewFile_thenCorrect()
throws IOException, InterruptedException {
// Assign
CountDownLatch latch = new CountDownLatch(1);
Context context = Robolectric.setupService(CommonContextStub.class);
byte[] outBytes = "abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.UTF_8);
PrintLogger.initialize(context);
InputStream in = new ByteArrayInputStream(outBytes);
File file = new File(/* pathname= */context.getFilesDir() + "/dummy");
Signal<Boolean> signal = Signal.create();
// Assert
signal.onNext(bool -> {
latch.countDown();
assertThat(file.length()).isEqualTo(outBytes.length);
});
// Act
DfuUtil.inputStreamToFile(in, file).forward(signal);
latch.await(/* timeout= */5, TimeUnit.SECONDS);
}
@Test
public void givenNonExistentFilePath_whenReturnEmptyPair_thenCorrect() throws FileNotFoundException {
// Assign
Context context = Robolectric.setupService(CommonContextStub.class);
File file = new File(/* pathname= */context.getFilesDir() + "/FileNoExists");
// Act
Pair<InputStream, Long> pair = DfuUtil.getFileInputStream(file.getPath());
// Assert
assertThat(pair.first).isNull();
assertThat(pair.second).isEqualTo(/* expected= */0);
}
@Test
public void givenCorrectFilePath_whenReturnCorrectPair_thenCorrect() throws IOException {
// Assign
Context context = Robolectric.setupService(CommonContextStub.class);
PrintLogger.initialize(context);
File file = new File(/* pathname= */context.getFilesDir() + "/FileExists");
file.createNewFile();
byte[] outBytes = "WriteThisForTest".getBytes(StandardCharsets.UTF_8);
InputStream in = new ByteArrayInputStream(outBytes);
DfuUtil.inputStreamToFile(in, file);
// Act
Pair<InputStream, Long> pair = DfuUtil.getFileInputStream(file.getPath());
// Assert
assertThat(pair.first).isNotNull();
assertThat(pair.second).isEqualTo(file.length());
}
} |
Java | public class UploadConfirmFragment extends AbstractExplorerPage {
@Required
@FindBy(xpath = "//input[@name='nxdistribution:name']")
public WebElement nameInput;
@Required
@FindBy(xpath = "//input[@name='nxdistribution:version']")
public WebElement versionInput;
@Required
@FindBy(xpath = "//input[@name='nxdistribution:key']")
public WebElement keyInput;
@Required
@FindBy(xpath = "//input[@name='dc:title']")
public WebElement titleInput;
@Required
@FindBy(xpath = "//input[@id='doImport']")
public WebElement importButton;
public UploadConfirmFragment(WebDriver driver) {
super(driver);
}
@Override
public void check() {
// NOOP
}
public void confirmUpload(String newName, String newVersion) {
if (newName != null) {
nameInput.clear();
nameInput.sendKeys(newName);
// just for display in tests
titleInput.clear();
titleInput.sendKeys(newName);
}
if (newVersion != null) {
versionInput.clear();
versionInput.sendKeys(newVersion);
}
keyInput.clear();
keyInput.sendKeys(String.format("%s-%s", nameInput.getAttribute("value"), versionInput.getAttribute("value")));
Locator.scrollAndForceClick(importButton);
By headerLocator = By.xpath("//h1");
Locator.waitUntilElementPresent(headerLocator);
assertEquals("Distribution uploaded successfully", driver.findElement(headerLocator).getText());
waitForAsyncWork();
}
} |
Java | public final class ValidateUtil {
public final static char UPN_SEPARATOR = '@';
public final static char NETBIOS_SEPARATOR = '\\';
public final static String spn_prefix = "STS/";
/**
* Validate the the given value is a positive number.
*
* @param fieldValue
* field value to validate
* @param fieldName
* field name
*
* @throws IllegalArgumentException
* on validation failure
*/
public static void validatePositiveNumber(long fieldValue, String fieldName) {
if (fieldValue <= 0) {
logAndThrow(String.format("%s should be a positive number: %d",
fieldName, fieldValue));
}
}
/**
* Validate the the given value is a non-negative number.
*
* @param fieldValue
* field value to validate
* @param fieldName
* field name
*
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateNonNegativeNumber(long fieldValue, String fieldName) {
if (fieldValue < 0) {
logAndThrow(String.format("%s should be a non-negative number: %d",
fieldName, fieldValue));
}
}
/**
* Same as {@link #validateNotNull(Object, String)} but just for {@code
* null} value
*
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateNotNull(Object fieldValue, String fieldName) {
if (fieldValue == null) {
logAndThrow(String.format("'%s' value should not be NULL", fieldName));
}
}
/**
* Validates that given value is <code>null</code>.
*
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateNull(Object fieldValue, String fieldName) {
if (fieldValue != null) {
logAndThrow(String.format("'%s' value should be NULL", fieldName));
}
}
/**
* Validates the given value forms a valid URI
* @param uri URI to be validated
* @param fieldName field name corresponding to the URI
* @throws IllegalArgumentException on validation failure
*/
public static void validateURI(String uri, String fieldName) {
validateNotNull(uri, fieldName);
try {
URI test_uri = new URI(uri);
} catch (URISyntaxException e) {
logAndThrow(String.format("%s' URI is invalid - %s. %s", uri, fieldName, e.toString()));
}
}
/**
* Validates that given certificate is <code>valid</code>.
* clockTolerance - value of current clock tolerance in milliseconds
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateSolutionDetail(SolutionDetail fieldValue, String fieldName, long clockTolerance) {
X509Certificate cert = fieldValue.getCertificate();
ValidateUtil.validateNotNull(cert, "Solution user certificate");
try
{
cert.checkValidity();
}
catch(CertificateException ex)
{
if (ex instanceof CertificateNotYetValidException)
{
// Check to see whether certificate is within clock tolerance
// if so do not throw, cert passes the validation
if (cert.getNotBefore().getTime() <= System.currentTimeMillis() + clockTolerance)
{
return;
}
}
if (ex instanceof CertificateExpiredException)
{
// Check to see whether certificate is within clock tolerance
// if so do not throw, cert passes the validation
if (cert.getNotAfter().getTime() >= System.currentTimeMillis() - clockTolerance)
{
return;
}
}
logAndThrow(String.format("'%s' certificate is invalid - " +
"certificateException %s", fieldName, ex.toString()));
}
}
/**
* Validates that given certificate type is <code>valid</code>.
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateCertType(CertificateType fieldValue, String fieldName)
{
if (fieldValue != CertificateType.LDAP_TRUSTED_CERT && fieldValue != CertificateType.STS_TRUST_CERT)
{
logAndThrow(String.format("'%s' value is invalid certificate type", fieldName));
}
}
/**
* Checks validity of the given certificate.
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateCertificate(X509Certificate cert)
{
try {
cert.checkValidity();
} catch (Exception e) {
logAndThrow(String.format("Certificate is not valid: %s", e.getMessage()));
}
}
/**
* Check whether given object value is empty. Depending on argument runtime
* type <i>empty</i> means:
* <ul>
* <li>for java.lang.String type - {@code null} value or empty string</li>
* <li>for array type - {@code null} value or zero length array</li>
* <li>for any other type - {@code null} value</li>
* </ul>
* <p>
* Note that java.lang.String values should be handled by
* {@link #isEmpty(String)}
* </p>
*
* @param obj
* any object or {@code null}
*
* @return {@code true} when the object value is {@code null} or empty array
*/
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().equals(String.class)) {
return ((String) obj).isEmpty();
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof java.util.Collection<?>) {
return ((java.util.Collection<?>) obj).isEmpty();
}
if (obj instanceof java.util.Map<?, ?>) {
return ((java.util.Map<?, ?>) obj).isEmpty();
}
final String message = "String, java.lang.Array, java.util.Collection, "
+ "java.util.Map expected but " + obj.getClass().getName() + " was found ";
getLog().error(message);
throw new IllegalArgumentException(message);
}
/**
* Validates that given value is not empty (as defined by
* {@link #isEmpty(Object)} contract). If validation check fails -
* {@link IllegalArgumentException} will be thrown.
* <p>
* Useful for validation of required input arguments passed by end user at
* public methods, etc.
*
* @param fieldValue
* field value to validate
* @param fieldName
* field name
*
* @throws IllegalArgumentException
* on validation failure
*/
public static void validateNotEmpty(Object fieldValue, String fieldName) {
if (isEmpty(fieldValue)) {
logAndThrow(String.format("'%s' value should not be empty", fieldName));
}
}
public static void validateIdsDomainName(String domainName, DomainType domainType)
{
validateNotEmpty(domainName, "ids domainName");
}
/**
* Validate IdentityStoreData attributes. Includes:
* domainName format validation
* domainAliase format validation
*
*
* @param idsData
*/
public static void validateIdsDomainNameNAlias(IIdentityStoreData idsData)
{
if (idsData.getDomainType().equals(DomainType.LOCAL_OS_DOMAIN))
return;
validateIdsDomainName(idsData.getName(), idsData.getDomainType());
if (null != idsData.getExtendedIdentityStoreData())
{
String domainAlias = idsData.getExtendedIdentityStoreData().getAlias();
if (domainAlias != null)
{
validateNotEmpty(domainAlias, "ids domainAlias");
}
}
}
public static String normalizeIdsKrbUserName(String krbUpn)
{
char[] validUpnSeparator = {UPN_SEPARATOR};
int idxSep = getValidIdxAccountNameSeparator(krbUpn, validUpnSeparator);
// if no '@' or multiple '@' or leading '@' exception is thrown
if (idxSep == -1 || idxSep == 0)
{
logAndThrow(String.format("userkrbPrincipal [%s] is not in valid UPN format ", krbUpn));
}
String userName = krbUpn.substring(0, idxSep);
validateNotEmpty(userName, "user account name in UPN");
String domain = krbUpn.substring(idxSep+1);
validateNotEmpty(domain, "user REALM in UPN");
return String.format("%s%c%s", userName, UPN_SEPARATOR, domain);
}
public static void validateUpn(String upn, String fieldName)
{
char[] validUpnSeparator = {UPN_SEPARATOR};
int idxSep = getValidIdxAccountNameSeparator(upn, validUpnSeparator);
// if no '@' or multiple '@' or leading '@' exception is thrown
if (idxSep == -1 || idxSep == 0)
{
logAndThrow(String.format("%s=[%s] is invalid: not a valid UPN format ", fieldName, upn));
}
String userName = upn.substring(0, idxSep);
validateNotEmpty(userName, "%s=[%s] is invalid: user name in UPN cannot be empty.");
String domain = upn.substring(idxSep+1);
validateNotEmpty(domain, "%s=[%s] is invalid: domain suffix in UPN cannot be empty.");
}
public static void validateNetBios(String netbiosName, String fieldName)
{
char[] validUpnSeparator = {NETBIOS_SEPARATOR};
int idxSep = getValidIdxAccountNameSeparator(netbiosName, validUpnSeparator);
// if no '\\' or multiple '\\' or leading '\\' exception is thrown
if (idxSep == -1 || idxSep == 0)
{
logAndThrow(String.format("%s=[%s] is invalid: not a valid netbios name format ", fieldName, netbiosName));
}
String userName = netbiosName.substring(0, idxSep);
validateNotEmpty(userName, "%s=[%s] is invalid: user name in netbios name cannot be empty.");
String domain = netbiosName.substring(idxSep+1);
validateNotEmpty(domain, "%s=[%s] is invalid: domain suffix in netbios name canot be empty.");
}
public static String validateIdsUserName(String userName, IdentityStoreType idsType, AuthenticationType authType)
{
// userName is used to bind to IDP
// (1) Doing a kerberos bind, userName is in upn@REALM format
// (2) Doing a simple bind to OpenLdap and vmware directory userName is in DN format
// (3) Doing a simple bind to AD over LDAP userName can be in DN format, upn or NetBios\\userName
if (authType == AuthenticationType.PASSWORD)
{
if (isValidDNFormat(userName))
{
return userName;
}
else if (idsType != IdentityStoreType.IDENTITY_STORE_TYPE_LDAP_WITH_AD_MAPPING)
{
logAndThrow(String.format("userName [%s] is not in valid DN format ", userName));
}
// validate userName to be UPN format
try
{
validateUpn(userName, "userName in UPN format");
}
catch(Exception e)
{
// validate userName to be Netbios\\userName
validateNetBios(userName, "userName in Netbios format");
}
return userName;
}
else if (authType == AuthenticationType.USE_KERBEROS)
{
try
{
return normalizeIdsKrbUserName(userName);
} catch (Exception e) {
logAndThrow(String.format("userName [%s] is not in valid kerberos UPN format ", userName));
}
}
else
{
logAndThrow(String.format("Unsupported IDS authentication type"));
}
return null;
}
// Simple validation of DN format. True: succeeded in validation.
// This method is not enforcing non-emptiness.
public static void validateDNFormat(String dnString) {
if (!isValidDNFormat(dnString)) {
throw new IllegalArgumentException(String.format("dnString [%s] is not in valid DN format ", dnString));
}
}
// RFC 4512: keystring(descr), numericoid
private static Pattern attributeTypePattern = Pattern.compile("(([a-zA-Z]([a-zA-Z0-9\\x2D])*)|(([0-9]|([1-9]([0-9])+))(\\x2E([0-9]|([1-9]([0-9])+)))+))([ ])*\\=");
// we will not validate the whole dn format syntax at the moment, but will check that the string comtain at least one instance of
// <attributeType>= sequence
public static boolean isValidDNFormat(String dnString)
{
boolean isValid = false;
if (dnString != null && !dnString.isEmpty() )
{
Matcher m = attributeTypePattern.matcher(dnString);
isValid = m.find();
}
return isValid;
}
/**
* Validate extended IdentityStoreData attributes that should be in DN format.
*
* The attributes are:
* userName format validation
* userBaseDN format validation
* groupBaseDN format validation
*
* @param idsData
*/
public static void validateIdsUserNameAndBaseDN(IIdentityStoreData idsData)
{
if (idsData.getDomainType().equals(DomainType.LOCAL_OS_DOMAIN))
return;
IIdentityStoreDataEx idsEx = idsData.getExtendedIdentityStoreData();
if (null == idsEx) {
return;
}
if (!idsData.getExtendedIdentityStoreData().useMachineAccount())
{
validateIdsUserName(idsEx.getUserName(),
idsData.getExtendedIdentityStoreData().getProviderType(),
idsData.getExtendedIdentityStoreData().getAuthenticationType());
}
// for AD IWA, skip groupBaseDN and userBaseDN check.
if ( !(idsData.getExtendedIdentityStoreData().getProviderType()
== IdentityStoreType.IDENTITY_STORE_TYPE_ACTIVE_DIRECTORY &&
idsData.getExtendedIdentityStoreData().getAuthenticationType()
== AuthenticationType.USE_KERBEROS
))
{
String groupBaseDN = idsEx.getGroupBaseDn();
try {
validateDNFormat(groupBaseDN);
} catch (Exception e) {
logAndThrow(String.format("groupBaseDN [%s] is not in valid DN format ", groupBaseDN));
}
String userBaseDN = idsEx.getUserBaseDn();
try {
validateDNFormat(userBaseDN);
} catch (Exception e) {
logAndThrow(String.format("userBaseDN [%s] is not in valid DN format ", userBaseDN));
}
}
}
public static int getValidIdxAccountNameSeparator(String userPrincipal, char[] validAccountNameSep)
{
// separator scan
// validate there is no more than one separator is used
int latestResult = -1; // not found
int totalSepCount = 0;
for (char sep : validAccountNameSep)
{
int count = StringUtils.countMatches(userPrincipal, String.valueOf(sep));
totalSepCount += count;
if (totalSepCount > 1)
{
logAndThrow(String.format(
"Invalid user principal format [%s]: only one separator of '@' or '\' is allowed.",
userPrincipal));
}
if (count == 1)
{
latestResult = userPrincipal.indexOf(sep);
}
}
return latestResult;
}
private static void logAndThrow(String msg) {
DiagnosticsLoggerFactory.getLogger(ValidateUtil.class).error(msg);
throw new IllegalArgumentException(msg);
}
private static IDiagnosticsLogger getLog() {
return DiagnosticsLoggerFactory.getLogger(ValidateUtil.class);
}
private ValidateUtil() {
// prevent instantiation
}
} |
Java | abstract class AbstractTestBuilder<R, T extends Producer<R>, S extends AbstractTestBuilder<R, T, S>>
extends AbstractCloneable<S> {
/**
* The primary test subject of this test.
*/
T _testSubject;
/**
* A list of nodes that should be equivalent in both behavior and as reported by equals()
*/
final List<T> _equivalents = new ArrayList<>();
/**
* A list of nodes that should not be equivalent in behavior or as reported by equals()
*/
final List<T> _nonEquivalents = new ArrayList<>();
/**
* A list of outputs testers. Each should return true if the output is satisfactory.
*/
final List<Predicate<? super R>> _outputsTesters = new ArrayList<>();
/**
* A list of testers for the reduced DAG. Each tester will receive the stream of producers retrieved by the
* {@code producers()} method on the reduced DAG and should return true if it is as expected.
*/
final List<Predicate<Stream<LinkedStack<Producer<?>>>>> _reductionTesters = new ArrayList<>();
/**
* True if all outputs tested (for generators) or the outputs corresponding to every input (for child nodes like
* transformers) should be distinct.
*/
boolean _distinctOutputs = false;
/**
* True if {@link Producer#validate()} should not be used to validate producers.
*/
boolean _skipValidation = false;
Type _resultSupertype = null;
/**
* Creates a new instance that will test the provided Dagli node.
*
* @param testSubject the primary test subject
*/
AbstractTestBuilder(T testSubject) {
_testSubject = testSubject;
}
/**
* @return a clone of this tester
*/
@Override
public S clone() {
return super.clone();
}
/**
* Adds to this test a node that should be logically equivalent to the primary test subject.
*
* @param other the other, equivalent node.
* @return this instance
*/
@SuppressWarnings("unchecked")
public S equalTo(T other) {
_equivalents.add(other);
return (S) this;
}
/**
* Adds to this test a node that should be logically distinct, as reported by equals(), from the primary test subject.
*
* @param other the other, non-equivalent node.
* @return this instance
*/
@SuppressWarnings("unchecked")
public S notEqualTo(T other) {
_nonEquivalents.add(other);
return (S) this;
}
/**
* Adds a check to verify that the tested producer's reported result supertype <strong>exactly</strong> matches the
* provided type. Most implementations use Dagli's default implementation for determining the result supertype, so
* testing is generally only required when this implementation is overridden.
*
* @param supertype the result supertype that should be reported by the producer
* @return this instance
*/
@SuppressWarnings("unchecked")
public S resultSupertype(Type supertype) {
_resultSupertype = supertype;
return (S) this;
}
/**
* Calls the provided <code>tester</code> on:
* (1) The primary test subject
* (2) The serialized and then deserialized copy of the test subject
* (3) Each "equivalent" node
* (4) The serialized and then deserialized copy of each "equivalent" node
*
* @param tester the testing method
*/
void checkAll(Consumer<T> tester) {
tester.accept(_testSubject);
tester.accept(serializeAndDeserialize(_testSubject));
_equivalents.forEach(tester);
_equivalents.stream().map(AbstractTestBuilder::serializeAndDeserialize).forEach(tester);
}
/**
* Simple wrapper for a predicate that implements {@link Object#toString()}
*
* @param <R> the type of result of the predicate
*/
private static class NamedPredicate<R> implements Predicate<R> {
private final Predicate<R> _tester;
private final String _name;
public NamedPredicate(Predicate<R> tester, String name) {
_tester = tester;
_name = name;
}
@Override
public boolean test(R r) {
return _tester.test(r);
}
@Override
public String toString() {
return _name;
}
}
/**
* Adds a client-provided test that will check that the result of the tested node, returning true if the result is
* as expected, and false if the result is erroneous. For child nodes (those with inputs) each output check
* corresponds to an input sequence provided by input() such that the first input provided corresponds to the first
* output, the second input corresponds to the second output, etc.
*
* For child nodes, the number of output checks cannot be greater than the number of inputs. Generators don't have
* inputs and can have as many output checks as desired; these will check the result of the generator at increasing
* example indices (starting at 0).
*
* @param test the test to perform against the output of the node
* @param name a name for the test; this will be included in the thrown exception if the test fails
* @return this instance
*/
public S outputTest(Predicate<? super R> test, String name) {
return outputTest(new NamedPredicate<>(test, name));
}
/**
* Adds a client-provided test that will check that the result of the tested node, returning true if the result is
* as expected, and false if the result is erroneous. For child nodes (those with inputs) each output check
* corresponds to an input sequence provided by input() such that the first input provided corresponds to the first
* output, the second input corresponds to the second output, etc.
*
* For child nodes, the number of output checks cannot be greater than the number of inputs. Generators don't have
* inputs and can have as many output checks as desired; these will check the result of the generator at increasing
* example indices (starting at 0).
*
* @param test the test to perform against the output of the node
* @return this instance
*/
@SuppressWarnings("unchecked")
public S outputTest(Predicate<? super R> test) {
_outputsTesters.add(test);
return (S) this;
}
/**
* Adds test that will check that the result of the tested node is equal to the provided value. For child nodes
* (those with inputs) each output check corresponds to an input sequence provided by input() such that
* the first input provided corresponds to the first output, the second input corresponds to the second output, etc.
*
* For child nodes, the number of output checks cannot be greater than the number of inputs. Generators don't have
* inputs and can have as many output checks as desired; these will check the result of the generator at increasing
* example indices (starting at 0).
*
* @param output an expected output from the tested node
* @return this instance
*/
public S output(R output) {
return outputTest(new NamedPredicate<>(value -> Objects.equals(value, output), "== " + output));
}
/**
* Adds each expected output value from a collection; equivalent to calling {@link AbstractTestBuilder#output(Object)}
* for each value.
*
* @param outputs the output values to add
* @return this instance
*/
@SuppressWarnings("unchecked")
public S allOutputs(Iterable<? extends R> outputs) {
outputs.forEach(this::output);
return (S) this;
}
/**
* Adds each output test from a collection; equivalent to calling {@link AbstractTestBuilder#outputTest(Predicate)}
* for each test.
*
* @param outputTests the output tests to add
* @return this instance
*/
@SuppressWarnings("unchecked")
public S allOutputTests(Iterable<Predicate<? super R>> outputTests) {
outputTests.forEach(this::outputTest);
return (S) this;
}
/**
* Adds a tester that will examine a DAG containing created with the test subject as an output (if not a generator,
* it must have no more than 10 placeholders as ancestors) that has been reduced to the greatest extent possible
* ({@link com.linkedin.dagli.reducer.Reducer.Level#EXPENSIVE}).
*
* Each tester will receive the stream of producers retrieved by the {@code producers()} method on the reduced DAG and
* should return true if the producers in the reduced DAG are as expected.
*/
@SuppressWarnings("unchecked")
public S reductionTest(Predicate<Stream<LinkedStack<Producer<?>>>> reductionTester) {
_reductionTesters.add(reductionTester);
return (S) this;
}
/**
* If this method is called, producers will not be validated.
*
* This is not recommended, but may be useful if the tests can proceed on an invalid instance and for whatever reason
* creating a valid instance is too cumbersome.
*
* @return this instance
*/
@SuppressWarnings("unchecked")
public S skipValidation() {
return skipValidation(true);
}
/**
* If {@code skip} is true, producers will not be validated.
*
* Skipping validation is not recommended, but may be useful if the tests can proceed on an invalid instance and for
* whatever reason creating a valid instance is too cumbersome. Invalid producers are also likely to fail other tests
* which will themselves need to be skipped.
*
* @param skip whether to skip validation testing
* @return this instance
*/
@SuppressWarnings("unchecked")
public S skipValidation(boolean skip) {
_skipValidation = true;
return (S) this;
}
/**
* If this method is called, all outputs tested (for generators) or all outputs corresponding to every input (for
* child nodes like transformers) must be distinct (not evaluate as {@link Object#equals(Object)}).
*
* @return this instance
*/
@SuppressWarnings("unchecked")
public S distinctOutputs() {
_distinctOutputs = true;
return (S) this;
}
/**
* If <code>mustBeDistinct</code> is true, all outputs tested (for generators) or all outputs corresponding to every
* input (for child nodes like transformers) must be distinct (not evaluate as {@link Object#equals(Object)}).
*
* @return this instance
*/
@SuppressWarnings("unchecked")
S distinctOutputs(boolean mustBeDistinct) {
_distinctOutputs = mustBeDistinct;
return (S) this;
}
static void assertTrue(boolean value, String message) {
if (!value) {
throw new AssertionError(message);
}
}
static void assertEquals(Object a, Object b, String message) {
if (!Objects.equals(a, b)) {
throw new AssertionError(message + " (" + a + " != " + b + ")");
}
}
static void assertNotEquals(Object a, Object b, String message) {
if (Objects.equals(a, b)) {
throw new AssertionError(message + " (" + a + " == " + b + ")");
}
}
/**
* Runs the test. Failures will result in thrown exceptions; a successful test will return from this method without
* an exception being thrown.
*/
public void test() {
if (!_skipValidation) {
_testSubject.validate(); // instance must be valid for us to test it further
}
testEqualityForEach(_testSubject, _equivalents);
testNonEqualityForEach(_testSubject, _nonEquivalents);
testReduction();
// check for invalid names
assertTrue(!isNullOrEmpty(_testSubject.getShortName()), "A producer's short name must not be null or empty");
assertTrue(!isNullOrEmpty(_testSubject.getName()), "A producer's name must not be null or empty");
// check the reported result supertype
Type resultSupertype = Producer.getResultSupertype(_testSubject);
assertTrue(resultSupertype != null, "The producer erroneously reports a null result supertype");
if (_resultSupertype != null) {
assertEquals(_resultSupertype, resultSupertype, "The expected and reported result supertypes do not match");
}
}
private static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
void testReduction() {
if (_reductionTesters.isEmpty()) {
return;
}
DAGTransformer<R, ?> dag = DAGTransformer.withOutput(_testSubject).withReduction(Reducer.Level.EXPENSIVE);
for (int i = 0; i < _reductionTesters.size(); i++) {
assertTrue(_reductionTesters.get(i).test(dag.producers()),
"Reduction test #" + i + " (" + _reductionTesters.get(i) + ") failed");
}
}
static void testNonEqualityForEach(Object testSubject, List<?> nonEquivalents) {
if (nonEquivalents.isEmpty()) {
return;
}
Object deserializedTestSubject = serializeAndDeserialize(testSubject);
for (Object nonEquivalent : nonEquivalents) {
Object deserializedNonEquivalent = serializeAndDeserialize(nonEquivalent);
testNonEquality(testSubject, nonEquivalent);
testNonEquality(deserializedTestSubject, nonEquivalent);
testNonEquality(testSubject, deserializedNonEquivalent);
testNonEquality(deserializedTestSubject, deserializedNonEquivalent);
}
}
static void testEqualityForEach(Object testSubject, List<?> equivalents) {
if (equivalents.isEmpty()) {
return;
}
Object deserializedTestSubject = serializeAndDeserialize(testSubject);
for (Object equivalent : equivalents) {
Object deserializedEquivalent = serializeAndDeserialize(equivalent);
testEquality(testSubject, equivalent);
testEquality(deserializedTestSubject, equivalent);
testEquality(testSubject, deserializedEquivalent);
testEquality(deserializedTestSubject, deserializedEquivalent);
}
}
static void testNonEquality(Object object1, Object object2) {
assertEquals(object1, object2, "Non-equality test failed");
assertEquals(object2, object1, "Non-equality test failed; equals() method is not symmetric");
}
static void testEquality(Object object1, Object object2) {
assertEquals(object1, object2, "Equality test failed");
assertEquals(object2, object1, "Equality test failed; equals() method is not symmetric");
assertEquals(object1.hashCode(), object2.hashCode(), "Objects evaluating as equals() do not have same hashCode()");
}
/**
* Checks that the given object's class defined the serialVersionUID field.
*
* @param tested the object to test
*/
static void assertHasSerialVersionUID(Object tested) {
try {
tested.getClass().getDeclaredField("serialVersionUID");
} catch (NoSuchFieldException e) {
throw new AssertionError(tested.getClass().getName() + " does not define serialVersionUID", e);
}
}
/**
* Serializes and deserializes the provided object, testing that the deserialized copy is equivalent to the original.
* Useful for testing if serialization and deserialization break or otherwise alter an object.
*
* @param obj the object to serialize and then deserialize
* @param <P> the type of object
* @return the deserialized object
*/
@SuppressWarnings("unchecked") // unchecked cast vetted by comparison of classes in subsequent assertEquals()
static <P> P serializeAndDeserialize(P obj) {
assertHasSerialVersionUID(obj);
final P result;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
result = (P) ois.readObject();
} catch (Exception e) {
throw Exceptions.asRuntimeException(e);
}
assertEquals(result.getClass(),
obj.getClass(), "Object is not the same class after serializing and deserializing!");
assertEquals(result, obj, "Object does not compare as equals() after serializing and deserializing!");
assertEquals(result.hashCode(), obj.hashCode(),
"Object does not have consistent hashCode() after serializing and deserializing!");
return result;
}
} |
Java | private static class NamedPredicate<R> implements Predicate<R> {
private final Predicate<R> _tester;
private final String _name;
public NamedPredicate(Predicate<R> tester, String name) {
_tester = tester;
_name = name;
}
@Override
public boolean test(R r) {
return _tester.test(r);
}
@Override
public String toString() {
return _name;
}
} |
Java | public class PilotingItfActivationController {
/** Drone controller that uses this activation controller. */
@NonNull
private final DroneController mDroneController;
/** Used to encode piloting commands to send in the non-ack command loop. */
@NonNull
private final PilotingCommand.Encoder mPilotingCommandEncoder;
/** Default piloting interface. */
@NonNull
private final ActivablePilotingItfController mDefaultPilotingItf;
/** Currently active piloting interface. {@code null} when the drone is not connected. */
@Nullable
private ActivablePilotingItfController mCurrentPilotingItf;
/** Piloting interface to activate after deactivation of the current one. */
@Nullable
private ActivablePilotingItfController mNextPilotingItf;
/** {@code true} when drone protocol-level connection is complete, otherwise {@code false}. */
private boolean mConnected;
/**
* Constructor.
*
* @param droneController drone controller that uses this activation controller
* @param pilotingCommandEncoder piloting command encoder
* @param defaultPilotingItfFactory factory used to build the default piloting interface of this drone controller
*/
PilotingItfActivationController(@NonNull DroneController droneController,
@NonNull PilotingCommand.Encoder pilotingCommandEncoder,
@NonNull ActivablePilotingItfController.Factory defaultPilotingItfFactory) {
mDroneController = droneController;
mPilotingCommandEncoder = pilotingCommandEncoder;
mDefaultPilotingItf = defaultPilotingItfFactory.create(this);
mDroneController.registerComponentControllers(mDefaultPilotingItf);
}
/**
* Gets the drone controller that owns this piloting interfaces activation controller.
*
* @return the drone controller
*/
@NonNull
public final DroneController getDroneController() {
return mDroneController;
}
/**
* Activates the piloting interface of the given controller.
*
* @param pilotingItf piloting interface controller whose interface must be activated
*
* @return {@code true} if the operation could be initiated, otherwise {@code false}
*/
public boolean activate(@NonNull ActivablePilotingItfController pilotingItf) {
if (ULog.d(TAG_PITF)) {
ULog.d(TAG_PITF, this + " Received activation request for " + pilotingItf);
}
if (pilotingItf != mCurrentPilotingItf && pilotingItf.canActivate()) {
if (mCurrentPilotingItf == null) {
pilotingItf.requestActivation();
return true;
} else if (mCurrentPilotingItf.canDeactivate()) {
mNextPilotingItf = pilotingItf;
mCurrentPilotingItf.requestDeactivation();
return true;
}
}
return false;
}
/**
* Deactivates the piloting interface of the given controller.
* <p>
* Only the current, non-default, piloting interface can be deactivated.
*
* @param pilotingItf piloting interface controller whose interface must be deactivated
*
* @return {@code true} if the operation could be initiated, otherwise {@code false}
*/
public boolean deactivate(@NonNull ActivablePilotingItfController pilotingItf) {
if (ULog.d(TAG_PITF)) {
ULog.d(TAG_PITF, this + " Received deactivation request for " + pilotingItf);
}
if (pilotingItf == mCurrentPilotingItf && pilotingItf != mDefaultPilotingItf && pilotingItf.canDeactivate()) {
mCurrentPilotingItf.requestDeactivation();
return true;
}
return false;
}
/**
* Called back when the drone has connected.
*/
public void onConnected() {
mConnected = true;
// reset piloting command values and sequence number
mPilotingCommandEncoder.reset();
// if no piloting itf is activated when connection is over, then fallback to the default one
if (mCurrentPilotingItf == null) {
if (ULog.d(TAG_PITF)) {
ULog.d(TAG_PITF, this + " Activating default piloting itf after drone connection");
}
mDefaultPilotingItf.requestActivation();
}
}
/**
* Called back when the drone has disconnected.
*/
public void onDisconnected() {
mConnected = false;
mCurrentPilotingItf = mNextPilotingItf = null;
}
/**
* Called back when a piloting interface declares itself inactive (either idle or unavailable).
*
* @param pilotingItf piloting interface controller whose interface is now idle
*/
public void onInactive(@NonNull ActivablePilotingItfController pilotingItf) {
if (pilotingItf == mCurrentPilotingItf) {
mCurrentPilotingItf = null;
}
if (mConnected && mCurrentPilotingItf == null) {
if (mNextPilotingItf != null) {
mNextPilotingItf.requestActivation();
mNextPilotingItf = null;
} else { // fallback on the default interface
mDefaultPilotingItf.requestActivation();
}
}
}
/**
* Called back when a piloting interface declares itself active.
*
* @param pilotingItf piloting interface controller whose interface is now active
* @param needsPilotingCommandLoop {@code true} if the piloting interface needs the piloting command loop to be
* started, otherwise {@code false}
*/
public void onActive(@NonNull ActivablePilotingItfController pilotingItf, boolean needsPilotingCommandLoop) {
if (pilotingItf != mCurrentPilotingItf) {
if (mCurrentPilotingItf != null) {
mCurrentPilotingItf.getPilotingItf().updateState(Activable.State.IDLE).notifyUpdated();
}
mCurrentPilotingItf = pilotingItf;
if (needsPilotingCommandLoop) {
mPilotingCommandEncoder.reset();
startPilotingCommandLoop();
} else {
stopPilotingCommandLoop();
}
}
}
/**
* Called back when a piloting interface forwards a piloting command roll change.
*
* @param pilotingItf piloting interface from which the change originates
* @param roll new roll value
*/
public void onRoll(@NonNull ActivablePilotingItfController pilotingItf, int roll) {
if (pilotingItf == mCurrentPilotingItf && mPilotingCommandEncoder.setRoll(roll)) {
mDroneController.onPilotingCommandChanged(mPilotingCommandEncoder.getPilotingCommand());
}
}
/**
* Called back when a piloting interface forwards a piloting command pitch change.
*
* @param pilotingItf piloting interface from which the change originates
* @param pitch new pitch value
*/
public void onPitch(@NonNull ActivablePilotingItfController pilotingItf, int pitch) {
if (pilotingItf == mCurrentPilotingItf && mPilotingCommandEncoder.setPitch(pitch)) {
mDroneController.onPilotingCommandChanged(mPilotingCommandEncoder.getPilotingCommand());
}
}
/**
* Called back when a piloting interface forwards a piloting command yaw change.
*
* @param pilotingItf piloting interface from which the change originates
* @param yaw new yaw value
*/
public void onYaw(@NonNull ActivablePilotingItfController pilotingItf, int yaw) {
if (pilotingItf == mCurrentPilotingItf && mPilotingCommandEncoder.setYaw(yaw)) {
mDroneController.onPilotingCommandChanged(mPilotingCommandEncoder.getPilotingCommand());
}
}
/**
* Called back when a piloting interface forwards a piloting command gaz change.
*
* @param pilotingItf piloting interface from which the change originates
* @param gaz new gaz value
*/
public void onGaz(@NonNull ActivablePilotingItfController pilotingItf, int gaz) {
if (pilotingItf == mCurrentPilotingItf && mPilotingCommandEncoder.setGaz(gaz)) {
mDroneController.onPilotingCommandChanged(mPilotingCommandEncoder.getPilotingCommand());
}
}
/**
* Starts the piloting command loop.
*/
private void startPilotingCommandLoop() {
DeviceController.Backend backend = mDroneController.getProtocolBackend();
if (backend != null) {
backend.registerNoAckCommandEncoders(mPilotingCommandEncoder);
}
}
/**
* Stops the piloting command loop.
*/
private void stopPilotingCommandLoop() {
DeviceController.Backend backend = mDroneController.getProtocolBackend();
if (backend != null) {
backend.unregisterNoAckCommandEncoders(mPilotingCommandEncoder);
}
mPilotingCommandEncoder.reset();
}
@NonNull
@Override
public String toString() {
return "PilotingItfActivationController [device:" + mDroneController.getUid() + "]";
}
/**
* Debug dump.
*
* @param writer writer to dump to
* @param prefix prefix string (usually indent) to prepend to each written dump line
*/
public void dump(@NonNull PrintWriter writer, @NonNull String prefix) {
writer.write(prefix + "PilotingItfPolicy:\n");
writer.write(prefix + "\t- Default PilotingItf: " + mDefaultPilotingItf + "\n");
writer.write(prefix + "\t- Active PilotingItf: " + mCurrentPilotingItf + "\n");
writer.write(prefix + "\t- Next PilotingItf: " + mNextPilotingItf + "\n");
}
} |
Java | public abstract class NullAwareSqlType<T> extends SqlType<T> {
/**
* Detects if there was a <code>null</code> reading and returns <code>null</code> if it was.
* Result set returns default value (e.g. 0) for many getters, therefore it detects if it was
* a null reading or it is a real value.
*/
@Override
public <E> E readValue(ResultSet rs, int index, Class<E> destinationType, int dbSqlType) throws SQLException {
T t = get(rs, index, dbSqlType);
if ((t == null) || (rs.wasNull())) {
return null;
}
return prepareGetValue(t, destinationType);
}
/**
* Detects <code>null</code> before storing the value into the database.
*/
@Override
public void storeValue(PreparedStatement st, int index, Object value, int dbSqlType) throws SQLException {
if (value == null) {
st.setNull(index, dbSqlType);
return;
}
super.storeValue(st, index, value, dbSqlType);
}
} |
Java | public class SimpleAttributeModifier extends AbstractBehavior
{
private static final long serialVersionUID = 1L;
/** The attribute */
private final String attribute;
/** The value to set */
private final CharSequence value;
/**
* Construct.
*
* @param attribute
* The attribute
* @param value
* The value
*/
public SimpleAttributeModifier(final String attribute, final CharSequence value)
{
if (attribute == null)
{
throw new IllegalArgumentException("Argument [attr] cannot be null");
}
if (value == null)
{
throw new IllegalArgumentException("Argument [value] cannot be null");
}
this.attribute = attribute;
this.value = value;
}
/**
* @return the attribute
*/
public final String getAttribute()
{
return attribute;
}
/**
* @return the value to set
*/
public final CharSequence getValue()
{
return value;
}
/**
* This method is deprecated, use the isEnabled(Component)
*
* @return true
* @deprecated use isEnabled(Component) now.
*/
@Deprecated
public final boolean isEnabled()
{
return true;
}
/**
* @see org.apache.wicket.behavior.AbstractBehavior#onComponentTag(org.apache.wicket.Component,
* org.apache.wicket.markup.ComponentTag)
*/
@Override
public void onComponentTag(final Component component, final ComponentTag tag)
{
if (isEnabled(component))
{
tag.getAttributes().put(attribute, value);
}
}
} |
Java | @Component
public class AuthorizationHelper {
/**
* Verifies if the user has an access role
* @param role
* @return
*/
public boolean hasRole(String role) {
Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder.getContext()
.getAuthentication().getAuthorities();
boolean hasRole = false;
for (GrantedAuthority authority : authorities) {
hasRole = authority.getAuthority().equals(role);
if (hasRole) {
break;
}
}
return hasRole;
}
/**
* Verifies if the authentication was made by a client (Client Credentials flow)
* @return
*/
public boolean isClientOnly(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null && auth instanceof OAuth2Authentication){
OAuth2Authentication oauth = (OAuth2Authentication)auth;
if(oauth.getUserAuthentication() != null && oauth.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken){
UsernamePasswordAuthenticationToken upt = (UsernamePasswordAuthenticationToken)oauth.getUserAuthentication();
HashMap<Object, Object> details = (HashMap<Object, Object>) upt.getDetails();
boolean clientOnly = (Boolean)details.get("clientOnly");
return clientOnly;
}
}
return false;
}
/**
* Return the client name (works only with Client Credentials authentications)
* @return
*/
public String getClientId(){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(isClientOnly()){
return ((OAuth2Authentication)auth).getName();
}
return null;
}
/**
* Return the username currently logged in
* This method make the code on controllers easier to unit test
*/
public String getUsername(Principal user){
return user.getName();
}
} |
Java | public class ReverseInteger {
public int reverse(int x) {
return reverseAsString(x);
}
private int reverseAsString(int x) {
String plus = "";
if (x < 0) {
plus = "-";
x = -x;
}
String xs = "" + x;
char[] chars = xs.toCharArray();
String rxs = plus;
int N = chars.length -1;
for (int i = N; i >= 0; i--) {
if (chars[i] != '-')
rxs += chars[i];
}
if(new Long(rxs) > new Long(Integer.MAX_VALUE ) ||
new Long(rxs) < new Long(Integer.MIN_VALUE)) {
return 0;
}
return new Integer(rxs);
}
public static void main(String[] args) {
ReverseInteger obj = new ReverseInteger();
System.out.println(obj.reverseAsString(-123));
System.out.println(obj.reverseAsString(((1 << 31) - 2)));
System.out.println(obj.reverseAsString(1563847412));
System.out.println(obj.reverseAsString(-2147483412));
}
} |
Java | @RunWith(SpringRunner.class)
@SpringBootTest(classes = ShortcutmasterApp.class)
public class ExerciseResourceIntTest {
private static final String DEFAULT_LABEL = "AAAAAAAAAA";
private static final String UPDATED_LABEL = "BBBBBBBBBB";
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB";
private static final Integer DEFAULT_ORDER = 1;
private static final Integer UPDATED_ORDER = 2;
@Autowired
private ExerciseRepository exerciseRepository;
@Autowired
private ExerciseService exerciseService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restExerciseMockMvc;
private Exercise exercise;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final ExerciseResource exerciseResource = new ExerciseResource(exerciseService);
this.restExerciseMockMvc = MockMvcBuilders.standaloneSetup(exerciseResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Exercise createEntity(EntityManager em) {
Exercise exercise = new Exercise()
.label(DEFAULT_LABEL)
.description(DEFAULT_DESCRIPTION)
.order(DEFAULT_ORDER);
return exercise;
}
@Before
public void initTest() {
exercise = createEntity(em);
}
@Test
@Transactional
public void createExercise() throws Exception {
int databaseSizeBeforeCreate = exerciseRepository.findAll().size();
// Create the Exercise
restExerciseMockMvc.perform(post("/api/exercises")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(exercise)))
.andExpect(status().isCreated());
// Validate the Exercise in the database
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeCreate + 1);
Exercise testExercise = exerciseList.get(exerciseList.size() - 1);
assertThat(testExercise.getLabel()).isEqualTo(DEFAULT_LABEL);
assertThat(testExercise.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testExercise.getOrder()).isEqualTo(DEFAULT_ORDER);
}
@Test
@Transactional
public void createExerciseWithExistingId() throws Exception {
int databaseSizeBeforeCreate = exerciseRepository.findAll().size();
// Create the Exercise with an existing ID
exercise.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restExerciseMockMvc.perform(post("/api/exercises")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(exercise)))
.andExpect(status().isBadRequest());
// Validate the Exercise in the database
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkLabelIsRequired() throws Exception {
int databaseSizeBeforeTest = exerciseRepository.findAll().size();
// set the field null
exercise.setLabel(null);
// Create the Exercise, which fails.
restExerciseMockMvc.perform(post("/api/exercises")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(exercise)))
.andExpect(status().isBadRequest());
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkOrderIsRequired() throws Exception {
int databaseSizeBeforeTest = exerciseRepository.findAll().size();
// set the field null
exercise.setOrder(null);
// Create the Exercise, which fails.
restExerciseMockMvc.perform(post("/api/exercises")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(exercise)))
.andExpect(status().isBadRequest());
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllExercises() throws Exception {
// Initialize the database
exerciseRepository.saveAndFlush(exercise);
// Get all the exerciseList
restExerciseMockMvc.perform(get("/api/exercises?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(exercise.getId().intValue())))
.andExpect(jsonPath("$.[*].label").value(hasItem(DEFAULT_LABEL.toString())))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].order").value(hasItem(DEFAULT_ORDER)));
}
@Test
@Transactional
public void getExercise() throws Exception {
// Initialize the database
exerciseRepository.saveAndFlush(exercise);
// Get the exercise
restExerciseMockMvc.perform(get("/api/exercises/{id}", exercise.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(exercise.getId().intValue()))
.andExpect(jsonPath("$.label").value(DEFAULT_LABEL.toString()))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.order").value(DEFAULT_ORDER));
}
@Test
@Transactional
public void getNonExistingExercise() throws Exception {
// Get the exercise
restExerciseMockMvc.perform(get("/api/exercises/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateExercise() throws Exception {
// Initialize the database
exerciseService.save(exercise);
int databaseSizeBeforeUpdate = exerciseRepository.findAll().size();
// Update the exercise
Exercise updatedExercise = exerciseRepository.findOne(exercise.getId());
// Disconnect from session so that the updates on updatedExercise are not directly saved in db
em.detach(updatedExercise);
updatedExercise
.label(UPDATED_LABEL)
.description(UPDATED_DESCRIPTION)
.order(UPDATED_ORDER);
restExerciseMockMvc.perform(put("/api/exercises")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedExercise)))
.andExpect(status().isOk());
// Validate the Exercise in the database
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeUpdate);
Exercise testExercise = exerciseList.get(exerciseList.size() - 1);
assertThat(testExercise.getLabel()).isEqualTo(UPDATED_LABEL);
assertThat(testExercise.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testExercise.getOrder()).isEqualTo(UPDATED_ORDER);
}
@Test
@Transactional
public void updateNonExistingExercise() throws Exception {
int databaseSizeBeforeUpdate = exerciseRepository.findAll().size();
// Create the Exercise
// If the entity doesn't have an ID, it will be created instead of just being updated
restExerciseMockMvc.perform(put("/api/exercises")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(exercise)))
.andExpect(status().isCreated());
// Validate the Exercise in the database
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteExercise() throws Exception {
// Initialize the database
exerciseService.save(exercise);
int databaseSizeBeforeDelete = exerciseRepository.findAll().size();
// Get the exercise
restExerciseMockMvc.perform(delete("/api/exercises/{id}", exercise.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Exercise> exerciseList = exerciseRepository.findAll();
assertThat(exerciseList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Exercise.class);
Exercise exercise1 = new Exercise();
exercise1.setId(1L);
Exercise exercise2 = new Exercise();
exercise2.setId(exercise1.getId());
assertThat(exercise1).isEqualTo(exercise2);
exercise2.setId(2L);
assertThat(exercise1).isNotEqualTo(exercise2);
exercise1.setId(null);
assertThat(exercise1).isNotEqualTo(exercise2);
}
} |
Java | public class PacketPlayInDifficultyLockEvent extends PacketPlayInEvent {
private boolean lock;
public PacketPlayInDifficultyLockEvent(Player injectedPlayer, PacketPlayInDifficultyLock packet) {
super(injectedPlayer);
Validate.notNull(packet);
lock = packet.b();
}
public PacketPlayInDifficultyLockEvent(Player injectedPlayer, boolean lock) {
super(injectedPlayer);
this.lock = lock;
}
public boolean isLock() {
return lock;
}
@Override
public Packet<PacketListenerPlayIn> getNMS() {
final PacketPlayInDifficultyLock packet = new PacketPlayInDifficultyLock();
Field.set(packet, "a", lock);
return packet;
}
@Override
public int getPacketID() {
return 0x11;
}
@Override
public String getProtocolURLString() {
return "https://wiki.vg/Protocol#Lock_Difficulty";
}
} |
Java | public class Totient {
/**
* Returns totient function fo BigInteger n. Uses Pollard Rho algorithm to
* factor n.<br>
*
* @param n
* BigInteger to factor.
* @return Totient(n), the number of positive integers less than n, which
* <br> are coprime with n.
*/
public static BigInteger totient(BigInteger n) {
if (n.compareTo(BigInteger.ONE) <= 0) {
return BigInteger.ONE;
}
ArrayList<BigInteger> factorList = Factorizor.factor(n, Factorizor.FactorMethod.RHO);
HashMap<BigInteger, Integer> map = HashMapBuilder.toHashMap(factorList);
BigInteger prod = BigInteger.ONE;
Iterator<Entry<BigInteger, Integer>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<BigInteger, Integer> entry = iter.next();
BigInteger primeVal = (entry.getKey().pow(entry.getValue()))
.subtract(entry.getKey().pow(entry.getValue() - 1));
prod = prod.multiply(primeVal);
}
return prod;
}
} |
Java | @Command(
name = "delete-profile",
description = "Delete the Workspace Manager default spend profile.")
public class DeleteProfile extends BaseCommand {
@CommandLine.Mixin DeletePrompt deletePromptOption;
/** Delete the WSM default spend profile. */
@Override
protected void execute() {
deletePromptOption.confirmOrThrow();
SpendProfileManagerService.fromContext().deleteDefaultSpendProfile();
OUT.println("Default WSM spend profile deleted successfully.");
}
} |
Java | public class ManagementBusDeploymentPluginRemote implements IManagementBusDeploymentPluginService {
static final private Logger LOG = LoggerFactory.getLogger(ManagementBusDeploymentPluginRemote.class);
@Override
public Exchange invokeImplementationArtifactDeployment(final Exchange exchange) {
LOG.debug("Trying to deploy IA on remote OpenTOSCA Container.");
final Message message = exchange.getIn();
// create empty request message (only headers needed)
final CollaborationMessage requestBody = new CollaborationMessage(new KeyValueMap(), null);
// perform remote deployment
final Exchange response =
RequestSender.sendRequestToRemoteContainer(message, RemoteOperations.INVOKE_IA_DEPLOYMENT, requestBody, 0);
// extract the endpoint URI from the response
final URI endpointURI = response.getIn().getHeader(MBHeader.ENDPOINT_URI.toString(), URI.class);
LOG.debug("Result of remote deployment: Endpoint URI: {}", endpointURI);
// add the header to the incoming exchange and return result
message.setHeader(MBHeader.ENDPOINT_URI.toString(), endpointURI);
return exchange;
}
@Override
public Exchange invokeImplementationArtifactUndeployment(final Exchange exchange) {
LOG.debug("Trying to undeploy IA on remote OpenTOSCA Container.");
final Message message = exchange.getIn();
// create empty request message (only headers needed)
final CollaborationMessage requestBody = new CollaborationMessage(new KeyValueMap(), null);
// perform remote undeployment
final Exchange response =
RequestSender.sendRequestToRemoteContainer(message, RemoteOperations.INVOKE_IA_UNDEPLOYMENT, requestBody,
0);
// extract the undeployment state from the response
final boolean state = response.getIn().getHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), boolean.class);
LOG.debug("Result of remote undeployment: Success: {}", state);
// add the header to the incoming exchange and return result
message.setHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), state);
return exchange;
}
@Override
/**
* {@inheritDoc}
*/
public List<String> getSupportedTypes() {
// This plug-in supports only the special type 'remote' which is used to forward deployment
// requests to other OpenTOSCA Containers.
return Collections.singletonList(Constants.REMOTE_TYPE);
}
@Override
/**
* {@inheritDoc}
*/
public List<String> getCapabilties() {
// This plug-in is intended to move deployment requests from one OpenTOSCA Container to
// another one. At the destination OpenTOSCA Container the deployment is done by one of the
// other available deployment plug-ins. Therefore, it has to be checked if this other
// deployment plug-in provides all needed capabilities before moving the request to the
// other Container. So, as this plug-in is only a redirection it does not provide any
// capabilities.
return new ArrayList<>();
}
} |
Java | public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.HEADERS : HttpLoggingInterceptor.Level.NONE);
OkHttpClient client = new OkHttpClient.Builder()
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
if(retrofit==null){
retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
} |
Java | public class CheckBoxBridge extends TwoWayViewBridge<CheckBox, Boolean> implements CompoundButton.OnCheckedChangeListener {
public CheckBoxBridge(Context context) {
this(context, null);
}
public CheckBoxBridge(Context context, AttributeSet attrs) {
view = attrs == null ? new CheckBox(context) : new CheckBox(context, attrs);
view.setOnCheckedChangeListener(this);
}
public void setValue(Value<Boolean> v) {
super.setValue(v);
String label = getLabel(v);
if (label != null) view.setText(label);
}
protected void updateViewFromValue() {
Object o = value.get();
view.setChecked(o == null ? false : (Boolean) o);
}
public void onCheckedChanged(CompoundButton v, boolean nu) {
updateValueFromView(nu);
}
} |
Java | @RestController
@RequestMapping(value = "/test")
public class TestController {
@ResponseBody
@RequestMapping("/query")
public String query(final String app) {
return "test: " + app;
}
} |
Java | public class EventsFragment extends Fragment {
ListView eventList;
CalendarView calendarView;
private EventAdapter eventAdapter;
List<Event> updatedList;
String currentDate, selectedDate;
SimpleDateFormat sdf;
Long date;
public EventsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_events, container, false);
calendarView = view.findViewById(R.id.events_calendar_view);
eventList = view.findViewById(R.id.lv_events);
date = calendarView.getDate();
sdf = new SimpleDateFormat("yyyy-MM-dd");
currentDate = sdf.format(new Date(calendarView.getDate()));
updatedList = new ArrayList<>();
final List<Event> events = FrontEngine.getInstance().getEventList();
for(int i = 0; i < events.size(); i++){
if(events.get(i).getHappeningDate().equals(currentDate)){
updatedList.add(events.get(i));
}
}
eventAdapter = new EventAdapter(view.getContext(), updatedList);
eventList.setAdapter(eventAdapter);
eventAdapter.notifyDataSetChanged();
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
date = view.getDate();
updatedList.clear();
String day = "";
if(dayOfMonth < 9){
day = String.format("%02d", dayOfMonth);
}
else {
day = String.valueOf(dayOfMonth);
}
for(int i = 0; i < events.size(); i++){
if(events.get(i).getHappeningDate().equals(year + "-" + month+1 + "-" + day)){
updatedList.add(events.get(i));
}
}
eventAdapter.notifyDataSetChanged();
//Toast.makeText(view.getContext(), "Year= " + year + " Month = " + month + " Date = " + dayOfMonth, Toast.LENGTH_LONG).show();
}
});
eventList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Event event = (Event) eventList.getItemAtPosition(position);
Intent newsIntent = new Intent(getContext(), EventActivity.class);
newsIntent.putExtra("event", event);
startActivity(newsIntent);
}
});
return view;
}
private void selectedDate(){
}
// the create options menu with a MenuInflater to have the menu from your fragment
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.findItem(R.id.action_events).setVisible(false);
menu.findItem(R.id.action_back).setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorite:
// Do onlick on menu action here
startActivity(new Intent(getActivity(), EventsSettingActivity.class));
getActivity().finish();
return true;
case R.id.action_back:
// Do onlick on menu action here
getActivity().onBackPressed();
return true;
}
return false;
}
} |
Java | public class Restaurant implements Parcelable {
@SuppressWarnings("unused")
public static final Parcelable.Creator<Restaurant> CREATOR = new Parcelable.Creator<Restaurant>() {
@Override
public Restaurant createFromParcel(Parcel in) {
return new Restaurant(in);
}
@Override
public Restaurant[] newArray(int size) {
return new Restaurant[size];
}
};
private String name;
private float rating;
private String ratingImageURL;
private String thumbnailURL;
private int reviewCount;
private String url;
private ArrayList<String> categories;
private ArrayList<String> address;
private String deal;
private double distance;
private double lat;
private double lon;
private boolean isSaved;
public Restaurant(String name, float rating, String ratingImageURL, String thumbnailURL, int reviewCount,
String url, ArrayList<String> categories, ArrayList<String> address,
String deal, double distance, double lat, double lon) {
this.name = name;
this.rating = rating;
this.ratingImageURL = ratingImageURL;
this.thumbnailURL = thumbnailURL;
this.reviewCount = reviewCount;
this.url = url;
this.categories = categories;
this.address = address;
this.deal = deal;
this.distance = distance;
this.lat = lat;
this.lon = lon;
}
protected Restaurant(Parcel in) {
name = in.readString();
rating = in.readFloat();
ratingImageURL = in.readString();
thumbnailURL = in.readString();
reviewCount = in.readInt();
url = in.readString();
if (in.readByte() == 0x01) {
categories = new ArrayList<>();
in.readList(categories, String.class.getClassLoader());
} else {
categories = null;
}
if (in.readByte() == 0x01) {
address = new ArrayList<>();
in.readList(address, String.class.getClassLoader());
} else {
address = null;
}
deal = in.readString();
distance = in.readDouble();
lat = in.readDouble();
lon = in.readDouble();
}
public String getName() {
return name;
}
public float getRating() {
return rating;
}
public int getReviewCount() {
return reviewCount;
}
public String getUrl() {
return url;
}
public ArrayList<String> getCategories() {
return categories;
}
public ArrayList<String> getAddress() {
return address;
}
public String getRatingImageURL() {
return ratingImageURL;
}
public String getThumbnailURL() {
return thumbnailURL;
}
public String getDeal() {
return deal;
}
public double getDistance() {
return distance;
}
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
public boolean isSaved() {
return isSaved;
}
public void setSaved(boolean b) {
this.isSaved = b;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeFloat(rating);
dest.writeString(ratingImageURL);
dest.writeString(thumbnailURL);
dest.writeInt(reviewCount);
dest.writeString(url);
if (categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(categories);
}
if (address == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(address);
}
dest.writeString(deal);
dest.writeDouble(distance);
dest.writeDouble(lat);
dest.writeDouble(lon);
}
@Override
public boolean equals(Object o) {
if (o instanceof Restaurant)
return this.url.equals(((Restaurant) o).url);
else return super.equals(o);
}
} |
Java | class PagingNavigatorFormPanel<T> extends Panel {
/**
* Creates a paging navigator form panel.
*
* @param table the parent table
*/
public PagingNavigatorFormPanel(DataTable<T, String> table) {
super("navigatorFormPanel");
add(new PagingNavigatorForm(table));
}
/**
* A form which allows to directly jump to pages.
*/
private class PagingNavigatorForm extends Form<Void> {
/**
* Creates a paging navigator form.
*
* @param table the parent table
*/
public PagingNavigatorForm(DataTable<T, String> table) {
super("navigatorForm");
TextField<String> pageTextField = new TextField<>("page", Model.of(""));
AjaxButton gotoButton = new GotoButton(table, pageTextField);
add(pageTextField.setOutputMarkupId(true));
add(gotoButton.setOutputMarkupId(true));
setDefaultButton(gotoButton);
}
}
/**
* An Ajax button which sends the user to a different page.
*/
private class GotoButton extends AjaxButton {
/**
* The parent table.
*/
private final DataTable<T, String> table;
/**
* A text field for page numbers.
*/
private final TextField<String> pageTextField;
/**
* Creates a go to button.
*
* @param table the parent table
* @param pageTextField a text field for page numbers
*/
public GotoButton(DataTable<T, String> table, TextField<String> pageTextField) {
super("gotoButton");
this.table = table;
this.pageTextField = pageTextField;
}
/**
* Called on form submit.
*
* @param target target that produces an Ajax response
* @param form the parent form
*/
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
String pageString = pageTextField.getModelObject();
Long pageCount = table.getPageCount();
Long currentPage = null;
if (pageString != null && pageString.matches("\\d+")) {
// data table pages are 0-based
currentPage = Long.valueOf(pageString) - 1L;
currentPage = (currentPage < 0L) ? 0L : currentPage;
currentPage = (currentPage >= pageCount) ? pageCount - 1L : currentPage;
}
if (currentPage != null && pageCount > 0) {
table.setCurrentPage(currentPage);
target.add(table);
}
pageTextField.setModelObject("");
target.add(pageTextField);
target.add(this);
}
}
} |
Java | private class PagingNavigatorForm extends Form<Void> {
/**
* Creates a paging navigator form.
*
* @param table the parent table
*/
public PagingNavigatorForm(DataTable<T, String> table) {
super("navigatorForm");
TextField<String> pageTextField = new TextField<>("page", Model.of(""));
AjaxButton gotoButton = new GotoButton(table, pageTextField);
add(pageTextField.setOutputMarkupId(true));
add(gotoButton.setOutputMarkupId(true));
setDefaultButton(gotoButton);
}
} |
Java | private class GotoButton extends AjaxButton {
/**
* The parent table.
*/
private final DataTable<T, String> table;
/**
* A text field for page numbers.
*/
private final TextField<String> pageTextField;
/**
* Creates a go to button.
*
* @param table the parent table
* @param pageTextField a text field for page numbers
*/
public GotoButton(DataTable<T, String> table, TextField<String> pageTextField) {
super("gotoButton");
this.table = table;
this.pageTextField = pageTextField;
}
/**
* Called on form submit.
*
* @param target target that produces an Ajax response
* @param form the parent form
*/
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
String pageString = pageTextField.getModelObject();
Long pageCount = table.getPageCount();
Long currentPage = null;
if (pageString != null && pageString.matches("\\d+")) {
// data table pages are 0-based
currentPage = Long.valueOf(pageString) - 1L;
currentPage = (currentPage < 0L) ? 0L : currentPage;
currentPage = (currentPage >= pageCount) ? pageCount - 1L : currentPage;
}
if (currentPage != null && pageCount > 0) {
table.setCurrentPage(currentPage);
target.add(table);
}
pageTextField.setModelObject("");
target.add(pageTextField);
target.add(this);
}
} |
Java | class MenuButtonMediator implements AppMenuObserver {
private Callback<AppMenuCoordinator> mAppMenuCoordinatorSupplierObserver;
private @Nullable AppMenuPropertiesDelegate mAppMenuPropertiesDelegate;
private AppMenuButtonHelper mAppMenuButtonHelper;
private ObservableSupplierImpl<AppMenuButtonHelper> mAppMenuButtonHelperSupplier;
private AppMenuHandler mAppMenuHandler;
private final BrowserStateBrowserControlsVisibilityDelegate mControlsVisibilityDelegate;
private final SetFocusFunction mSetUrlBarFocusFunction;
private final PropertyModel mPropertyModel;
private final Runnable mRequestRenderRunnable;
private final ThemeColorProvider mThemeColorProvider;
private final Activity mActivity;
private final KeyboardVisibilityDelegate mKeyboardDelegate;
private boolean mShouldShowAppUpdateBadge;
private final Supplier<Boolean> mIsActivityFinishingSupplier;
private int mFullscreenMenuToken = TokenHolder.INVALID_TOKEN;
private int mFullscreenHighlightToken = TokenHolder.INVALID_TOKEN;
private final Supplier<Boolean> mIsInOverviewModeSupplier;
private boolean mSuppressAppMenuUpdateBadge;
private Resources mResources;
private final OneshotSupplier<AppMenuCoordinator> mAppMenuCoordinatorSupplier;
private final Supplier<MenuButtonState> mMenuButtonStateSupplier;
private final Runnable mOnMenuButtonClicked;
private final int mUrlFocusTranslationX;
/**
* @param propertyModel Model to write property changes to.
* @param shouldShowAppUpdateBadge Whether the "update available" badge should ever be shown.
* @param isActivityFinishingSupplier Supplier for knowing if the embedding activity is in the
* process of finishing or has already been destroyed.
* @param requestRenderRunnable Runnable that requests a re-rendering of the compositor view
* containing the app menu button.
* @param themeColorProvider Provider of theme color changes.
* @param isInOverviewModeSupplier Supplier of overview mode state.
* @param controlsVisibilityDelegate Delegate for forcing persistent display of browser
* controls.
* @param setUrlBarFocusFunction Function that allows setting focus on the url bar.
* @param appMenuCoordinatorSupplier Supplier for the AppMenuCoordinator, which owns all other
* app menu MVC components.
* @param windowAndroid The WindowAndroid instance.
* @param menuButtonStateSupplier Suplier of {@link MenuButtonState}.
* @param onMenuButtonClicked Runnable to execute when menu button is clicked.
*/
MenuButtonMediator(PropertyModel propertyModel, boolean shouldShowAppUpdateBadge,
Supplier<Boolean> isActivityFinishingSupplier, Runnable requestRenderRunnable,
ThemeColorProvider themeColorProvider, Supplier<Boolean> isInOverviewModeSupplier,
BrowserStateBrowserControlsVisibilityDelegate controlsVisibilityDelegate,
SetFocusFunction setUrlBarFocusFunction,
OneshotSupplier<AppMenuCoordinator> appMenuCoordinatorSupplier,
WindowAndroid windowAndroid, Supplier<MenuButtonState> menuButtonStateSupplier,
Runnable onMenuButtonClicked) {
mPropertyModel = propertyModel;
mShouldShowAppUpdateBadge = shouldShowAppUpdateBadge;
mIsActivityFinishingSupplier = isActivityFinishingSupplier;
mRequestRenderRunnable = requestRenderRunnable;
mThemeColorProvider = themeColorProvider;
mIsInOverviewModeSupplier = isInOverviewModeSupplier;
mControlsVisibilityDelegate = controlsVisibilityDelegate;
mSetUrlBarFocusFunction = setUrlBarFocusFunction;
mThemeColorProvider.addTintObserver(this::onTintChanged);
mAppMenuCoordinatorSupplierObserver = this::onAppMenuInitialized;
mAppMenuCoordinatorSupplier = appMenuCoordinatorSupplier;
mAppMenuCoordinatorSupplier.onAvailable(mAppMenuCoordinatorSupplierObserver);
mActivity = windowAndroid.getActivity().get();
mResources = mActivity.getResources();
mAppMenuButtonHelperSupplier = new ObservableSupplierImpl<>();
mKeyboardDelegate = windowAndroid.getKeyboardDelegate();
mMenuButtonStateSupplier = menuButtonStateSupplier;
mOnMenuButtonClicked = onMenuButtonClicked;
mUrlFocusTranslationX =
mResources.getDimensionPixelSize(R.dimen.toolbar_url_focus_translation_x);
}
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
if (isVisible) {
// Defocus here to avoid handling focus in multiple places, e.g., when the
// forward button is pressed. (see crbug.com/414219)
mSetUrlBarFocusFunction.setFocus(false, OmniboxFocusReason.UNFOCUS);
View view = mActivity.getCurrentFocus();
if (view != null) {
// Dismiss keyboard in case the user was interacting with an input field on a
// website.
mKeyboardDelegate.hideKeyboard(view);
}
if (!mIsInOverviewModeSupplier.get() && isShowingAppMenuUpdateBadge()) {
// The app menu badge should be removed the first time the menu is opened.
removeAppMenuUpdateBadge(true);
mRequestRenderRunnable.run();
}
mFullscreenMenuToken =
mControlsVisibilityDelegate.showControlsPersistentAndClearOldToken(
mFullscreenMenuToken);
} else {
mControlsVisibilityDelegate.releasePersistentShowingToken(mFullscreenMenuToken);
}
if (isVisible) mOnMenuButtonClicked.run();
}
@Override
public void onMenuHighlightChanged(boolean isHighlighting) {
setMenuButtonHighlight(isHighlighting);
if (isHighlighting) {
mFullscreenHighlightToken =
mControlsVisibilityDelegate.showControlsPersistentAndClearOldToken(
mFullscreenHighlightToken);
} else {
mControlsVisibilityDelegate.releasePersistentShowingToken(mFullscreenHighlightToken);
}
}
void setClickable(boolean isClickable) {
mPropertyModel.set(MenuButtonProperties.IS_CLICKABLE, isClickable);
}
void setMenuButtonHighlight(boolean isHighlighting) {
mPropertyModel.set(MenuButtonProperties.IS_HIGHLIGHTING, isHighlighting);
}
void setAppMenuUpdateBadgeSuppressed(boolean isSuppressed) {
mSuppressAppMenuUpdateBadge = isSuppressed;
if (isSuppressed) {
removeAppMenuUpdateBadge(false);
} else if (isUpdateAvailable() && mShouldShowAppUpdateBadge) {
showAppMenuUpdateBadge(false);
}
}
void setVisibility(boolean visible) {
mPropertyModel.set(MenuButtonProperties.IS_VISIBLE, visible);
}
void updateReloadingState(boolean isLoading) {
if (mAppMenuPropertiesDelegate == null || mAppMenuHandler == null) {
return;
}
mAppMenuPropertiesDelegate.loadingStateChanged(isLoading);
mAppMenuHandler.menuItemContentChanged(R.id.icon_row_menu_id);
}
ObservableSupplier<AppMenuButtonHelper> getMenuButtonHelperSupplier() {
return mAppMenuButtonHelperSupplier;
}
void destroy() {
if (mAppMenuButtonHelper != null) {
mAppMenuHandler.removeObserver(this);
mAppMenuButtonHelper = null;
}
}
void updateStateChanged() {
if (mIsActivityFinishingSupplier.get() || !mShouldShowAppUpdateBadge) {
return;
}
if (isUpdateAvailable()) {
showAppMenuUpdateBadge(true);
mRequestRenderRunnable.run();
} else if (isShowingAppMenuUpdateBadge()) {
removeAppMenuUpdateBadge(true);
}
}
private void showAppMenuUpdateBadge(boolean animate) {
if (mSuppressAppMenuUpdateBadge) {
return;
}
MenuButtonState buttonState = mMenuButtonStateSupplier.get();
assert buttonState != null : "No button state when trying to show the badge.";
updateContentDescription(true, buttonState.menuContentDescription);
mPropertyModel.set(
MenuButtonProperties.SHOW_UPDATE_BADGE, new ShowBadgeProperty(true, animate));
}
private void removeAppMenuUpdateBadge(boolean animate) {
mPropertyModel.set(
MenuButtonProperties.SHOW_UPDATE_BADGE, new ShowBadgeProperty(false, animate));
updateContentDescription(false, 0);
}
private void onTintChanged(ColorStateList tintList, boolean useLight) {
mPropertyModel.set(MenuButtonProperties.THEME, new ThemeProperty(tintList, useLight));
}
/**
* Sets the content description for the menu button.
* @param isUpdateBadgeVisible Whether the update menu badge is visible.
* @param badgeContentDescription Resource id of the string to show if the update badge is
* visible.
*/
private void updateContentDescription(
boolean isUpdateBadgeVisible, int badgeContentDescription) {
if (isUpdateBadgeVisible) {
mPropertyModel.set(MenuButtonProperties.CONTENT_DESCRIPTION,
mResources.getString(badgeContentDescription));
} else {
mPropertyModel.set(MenuButtonProperties.CONTENT_DESCRIPTION,
mResources.getString(R.string.accessibility_toolbar_btn_menu));
}
}
/**
* Called when the app menu and related properties delegate are available.
*
* @param appMenuCoordinator The coordinator for interacting with the menu.
*/
private void onAppMenuInitialized(AppMenuCoordinator appMenuCoordinator) {
assert mAppMenuHandler == null;
AppMenuHandler appMenuHandler = appMenuCoordinator.getAppMenuHandler();
mAppMenuHandler = appMenuHandler;
mAppMenuHandler.addObserver(this);
mAppMenuButtonHelper = mAppMenuHandler.createAppMenuButtonHelper();
mAppMenuButtonHelper.setOnAppMenuShownListener(
() -> { RecordUserAction.record("MobileToolbarShowMenu"); });
mPropertyModel.set(MenuButtonProperties.APP_MENU_BUTTON_HELPER, mAppMenuButtonHelper);
mAppMenuButtonHelperSupplier.set(mAppMenuButtonHelper);
mAppMenuPropertiesDelegate = appMenuCoordinator.getAppMenuPropertiesDelegate();
}
/**
* @return Whether the badge is showing (either in the toolbar).
*/
private boolean isShowingAppMenuUpdateBadge() {
return mPropertyModel.get(MenuButtonProperties.SHOW_UPDATE_BADGE).mShowUpdateBadge;
}
private boolean isUpdateAvailable() {
return mMenuButtonStateSupplier.get() != null;
}
public Animator getUrlFocusingAnimator(boolean isFocusingUrl, boolean isRtl) {
float translationX;
float alpha;
if (isFocusingUrl) {
float density = mResources.getDisplayMetrics().density;
translationX = MathUtils.flipSignIf(mUrlFocusTranslationX, isRtl) * density;
alpha = 0.0f;
} else {
translationX = 0.0f;
alpha = 1.0f;
}
AnimatorSet animatorSet = new AnimatorSet();
Animator translationAnimator = PropertyModelAnimatorFactory.ofFloat(
mPropertyModel, MenuButtonProperties.TRANSLATION_X, translationX);
Animator alphaAnimator = PropertyModelAnimatorFactory.ofFloat(
mPropertyModel, MenuButtonProperties.ALPHA, alpha);
animatorSet.playTogether(translationAnimator, alphaAnimator);
return animatorSet;
}
} |
Java | public class FilterExistsAgg extends LeafAgg {
public FilterExistsAgg(String id, String fieldName) {
super(id, fieldName);
}
@Override
AggregationBuilder toBuilder() {
return filter(id(), QueryBuilders.existsQuery(fieldName()));
}
} |
Java | public final class QueryBuilder {
private QueryBuilder(){
}
/**
* Start building a new INSERT query.
*
* @param kind the kind of entity to insert.
* @return an in-construction INSERT query.
*/
public static Insert insert(final String kind) {
return new Insert(Key.builder(kind).build());
}
/**
* Start building a new INSERT query.
*
* @param kind the kind of entity to insert.
* @param id the key id of this entity to insert.
* @return an in-construction INSERT query.
*/
public static Insert insert(final String kind, final long id) {
return new Insert(Key.builder(kind, id).build());
}
/**
* Start building a new INSERT query.
*
* @param kind the kind of entity to insert.
* @param name the key name of this entity to insert.
* @return an in-construction INSERT query.
*/
public static Insert insert(final String kind, final String name) {
return new Insert(Key.builder(kind, name).build());
}
/**
* Start building a new INSERT query.
*
* @param key the key of this entity to insert.
* @return an in-construction INSERT query.
*/
public static Insert insert(final Key key) {
return new Insert(key);
}
/**
* Start building a new INSERT query.
*
* @param entity the entity to insert.
* @return an in-construction INSERT query.
*/
public static Insert insert(final Entity entity) {
return new Insert(entity);
}
/**
* Start building a new UPDATE query.
*
* @param kind the kind of entity to update.
* @return an in-construction UPDATE query.
*/
public static Update update(final String kind) {
return new Update(Key.builder().path(kind).build());
}
/**
* Start building a new UPDATE query.
*
* @param kind the kind of entity to update.
* @param id the key id of this entity to update.
* @return an in-construction UPDATE query.
*/
public static Update update(final String kind, final long id) {
return new Update(Key.builder().path(kind, id).build());
}
/**
* Start building a new UPDATE query.
*
* @param kind the kind of entity to update.
* @param name the key name of the entity to update.
* @return an in-construction UPDATE query.
*/
public static Update update(final String kind, final String name) {
return new Update(Key.builder().path(kind, name).build());
}
/**
* Start building a new UPDATE query.
*
* @param key the key of the entity to update.
* @return an in-construction UPDATE query.
*/
public static Update update(final Key key) {
return new Update(key);
}
/**
* Start building a new UPDATE query.
*
* @param entity the entity to update.
* @return an in-construction UPDATE query.
*/
public static Update update(final Entity entity) {
return new Update(entity);
}
/**
* Start building a new DELETE query.
*
* @param kind the kind of entity to delete.
* @param id the key id of this entity to delete.
* @return an in-construction DELETE query.
*/
public static Delete delete(final String kind, final long id) {
return new Delete(Key.builder().path(kind, id).build());
}
/**
* Start building a new DELETE query.
*
* @param kind the kind of entity to delete.
* @param name the key name of the entity to delete.
* @return an in-construction DELETE query.
*/
public static Delete delete(final String kind, final String name) {
return new Delete(Key.builder().path(kind, name).build());
}
/**
* Start building a new DELETE query.
*
* @param key the key of the entity to delete.
* @return an in-construction DELETE query.
*/
public static Delete delete(final Key key) {
return new Delete(key);
}
/**
* Start building a new ALLOCATE query.
*
* @param keys list of partial keys to allocate.
* @return an in-construction ALLOCATE query.
*/
public static AllocateIds allocate(final List<Key> keys) {
return new AllocateIds(keys);
}
/**
* Start building a new ALLOCATE query.
*
* @return an in-construction ALLOCATE query.
*/
public static AllocateIds allocate() {
return new AllocateIds();
}
/**
* Start building a new BATCH query.
* <p>
* This method will build a query for batching operations into a single
* call to Datastore.
* <p>
* NOTE: Use a transaction to make this batch operation atomic, otherwise
* and error might mean that some, none, or all of the requested operations
* have been performed.
*
* @return an in-construction BATCH query.
*/
public static Batch batch() {
return new Batch();
}
/**
* Start building a new KEYQUERY query.
* <p>
* You should use a {@code KeyQuery} to retrieve a single entity based
* on its key.
*
* @param kind the kind of entity to retrieve.
* @param id the key id of this entity to retrieve.
* @return an in-construction KEYQUERY query.
*/
public static KeyQuery query(final String kind, final long id) {
return new KeyQuery(Key.builder().path(kind, id).build());
}
/**
* Start building a new KEYQUERY query.
* <p>
* You should use a {@code KeyQuery} to retrieve a single entity based
* on its key.
*
* @param kind the kind of entity to retrieve.
* @param name the key name of this entity to retrieve.
* @return an in-construction KEYQUERY query.
*/
public static KeyQuery query(final String kind, final String name) {
return new KeyQuery(Key.builder().path(kind, name).build());
}
/**
* Start building a new KEYQUERY query.
* <p>
* Use a {@code KeyQuery} to retrieve a single entity based on its key.
*
* @param key the key of entity to retrieve.
* @return an in-construction KEYQUERY query.
*/
public static KeyQuery query(final Key key) {
return new KeyQuery(key);
}
/**
* Start building a new QUERY query.
* <p>
* Use a {@code Query} to retrieve one or more entities that satisfy a
* given criteria and order.
*
* @return an in-construction QUERY query.
*/
public static Query query() {
return new Query();
}
/**
* Creates an "equal" {@code Filter} stating the provided property
* must be equal to a given value.
*
* @param name the property name.
* @param value the value.
* @return a query filter.
*/
public static Filter eq(final String name, final Object value) {
return new Filter(name, Filter.Operator.EQUAL, Value.builder().value(value).build());
}
/**
* Creates an "less than" {@code Filter} stating the provided property
* must be less than a given value.
*
* @param name the property name.
* @param value the value.
* @return a query filter.
*/
public static Filter lt(final String name, final Object value) {
return new Filter(name, Filter.Operator.LESS_THAN, Value.builder().value(value).build());
}
/**
* Creates an "less than or equal" {@code Filter} stating the provided
* property must be less than or equal to a given value.
*
* @param name the property name.
* @param value the value.
* @return a query filter.
*/
public static Filter lte(final String name, final Object value) {
return new Filter(name, Filter.Operator.LESS_THAN_OR_EQUAL, Value.builder().value(value).build());
}
/**
* Creates an "greater than" {@code Filter} stating the provided property
* must be greater than a given value.
*
* @param name the property name.
* @param value the value.
* @return a query filter.
*/
public static Filter gt(final String name, final Object value) {
return new Filter(name, Filter.Operator.GREATER_THAN, Value.builder().value(value).build());
}
/**
* Creates an "greater than or equal" {@code Filter} stating the provided
* property must be greater than or equal to a given value.
*
* @param name the property name.
* @param value the value.
* @return a query filter.
*/
public static Filter gte(final String name, final Object value) {
return new Filter(name, Filter.Operator.GREATER_THAN_OR_EQUAL, Value.builder().value(value).build());
}
/**
* Creates an "ancestor" {@code Filter} stating the provided key must be
* an ancestor of the queried entities.
*
* @param kind the ancestor kind.
* @param id the ancestor key id.
* @return a query filter.
*/
public static Filter ancestor(final String kind, final long id) {
return new Filter("__key__", Filter.Operator.HAS_ANCESTOR, Value.builder().value(Key.builder(kind, id).build()).build());
}
/**
* Creates an "ancestor" {@code Filter} stating the provided key must be
* an ancestor of the queried entities.
*
* @param kind the ancestor kind.
* @param name the ancestor key name.
* @return a query filter.
*/
public static Filter ancestor(final String kind, final String name) {
return new Filter("__key__", Filter.Operator.HAS_ANCESTOR, Value.builder().value(Key.builder(kind, name).build()).build());
}
/**
* Creates an "ancestor" {@code Filter} stating the provided key must be
* an ancestor of the queried entities.
*
* @param key the ancestor key.
* @return a query filter.
*/
public static Filter ancestor(final Key key) {
return new Filter("__key__", Filter.Operator.HAS_ANCESTOR, Value.builder().value(key).build());
}
/**
* Ascending ordering for the provided property name.
*
* @param name the property name.
* @return the query ordering.
*/
public static Order asc(final String name) {
return new Order(name, Order.Direction.ASCENDING);
}
/**
* Descending ordering for the provided property name.
*
* @param name the property name.
* @return the query ordering.
*/
public static Order desc(final String name) {
return new Order(name, Order.Direction.DESCENDING);
}
/**
* Creates a {@code Group} stating the query should be grouped
* by the provided property name.
*
* @param name the name of the property to group by.
* @return a query grouping.
*/
public static Group group(final String name) {
return new Group(name);
}
} |
Java | public class NmmServiceImpl implements NmmService {
@Autowired
private NmmModelRepository modelRepository;
@Autowired
private Sender sender;
@Override
public NmmModel processNmmRequest(NmmRequest nmmRequest) {
NmmRequestValidator.validate(nmmRequest);
NmmModel model = new NmmModel.NmmModelBuilder()
.setMockVer(0)
.setScenario(nmmRequest.getScenario())
.setScenarioInfo(new ScenarioInfo())
.setResponse(nmmRequest.getResponse())
.build();
modelRepository.saveNmmModel(model);
sender.send(new NmmMessage(NmmOperation.CREATE, model));
return model;
}
@Override
public List<NmmModel> getNmmModelByServiceName(String serviceName) {
NmmRequestValidator.validateServiceName(serviceName);
return new ArrayList<>(
modelRepository.findNmmModelsByServiceName(serviceName).values());
}
@Override
public NmmModel getNmmModel(String serviceName, String scenarioId) {
NmmRequestValidator.validateServiceName(serviceName);
NmmRequestValidator.validateScenarioId(scenarioId);
return modelRepository.getNmmModel(serviceName, scenarioId);
}
@Override
public Long deleteNmmModelByScenarioId(String serviceName, String scenarioId) {
NmmRequestValidator.validateServiceName(serviceName);
NmmRequestValidator.validateScenarioId(scenarioId);
// TODO: publish DELETE NmmMessage
return modelRepository.deleteNmmModel(serviceName, scenarioId);
}
} |
Java | public final class EchoBreakpointHitParser extends AbstractReplyParser<EchoBreakpointHitReply> {
/**
* Creates a new Echo Breakpoint hit reply parser.
*
* @param clientReader Used to read messages sent by the debug client.
*/
public EchoBreakpointHitParser(final ClientReader clientReader) {
super(clientReader, DebugCommandType.RESP_BPE_HIT);
}
@Override
protected EchoBreakpointHitReply parseError(final int packetId) {
// TODO: There is no proper handling of errors on the side of the
// client yet.
throw new IllegalStateException("IE01082: Received invalid reply from the debug client");
}
@Override
public EchoBreakpointHitReply parseSuccess(final int packetId, final int argumentCount)
throws IOException {
final long tid = parseThreadId();
final byte[] data = parseData();
// Try to convert the byte data into valid register values.
try {
final RegisterValues registerValues = RegisterValuesParser.parse(data);
return new EchoBreakpointHitReply(packetId, 0, tid, registerValues);
} catch (final Exception e) {
CUtilityFunctions.logException(e);
return new EchoBreakpointHitReply(packetId, PARSER_ERROR, 0, null);
}
}
} |
Java | public class BabyTextView extends EditText {
private MovementMethodHandler m_handler;
private int m_lastY = 0;
private boolean m_shouldShowSelect = true;
private int m_slop;
public BabyTextView(Context context) {
super(context);
init();
}
public BabyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BabyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BabyTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
m_handler = new MovementMethodHandler(this);
m_slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
}
private boolean isJustify = false;
@Override
protected void onDraw(Canvas canvas) {
if (!isJustify) {
final int contentWidth = getWidth() - getPaddingLeft() - getPaddingRight();
setText(TextJustification.justify(getText().toString(), this, contentWidth), BufferType.EDITABLE);
isJustify = true;
}
super.onDraw(canvas);
}
@Override
protected boolean getDefaultEditable() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
m_lastY = (int) event.getY();
m_shouldShowSelect = true;
break;
case MotionEvent.ACTION_MOVE:
if (event.getY() - m_lastY >= m_slop) {
m_shouldShowSelect = false;
}
break;
case MotionEvent.ACTION_UP:
if (m_shouldShowSelect) {
selectWords(event);
}
}
//因为涉及滚动 所以还是要使用到super的method
super.onTouchEvent(event);
return true;
}
/**
* 单击选择单词
* @param event 事件
*/
private void selectWords(MotionEvent event) {
m_handler.selectWord(event);
}
/**
* @return 获得可见文字范围
*/
public Pair<Integer, Integer> getVisualScope() {
int first = getOffsetForPosition(getPaddingLeft(),getPaddingTop());
int last = getOffsetForPosition(getWidth() - getPaddingRight(),
getHeight() - getPaddingBottom());
if (first < 0) {
first = 0;
}
final int length = getEditableText().length();
if (last >= length) {
last = length - 1;
}
return new Pair<>(first, last);
}
/**
* 提醒text内容已经发生变化
*/
public void notifyTextHasChanged() {
isJustify = false;
invalidate();
}
} |
Java | public abstract class TableUpdater {
private static final Logger LOG = LoggerFactory.getLogger(TableUpdater.class);
private Map<String, TimeValue> cachedUpdates;
private final Object cachedUpdatesLock = new Object();
private Timer updateTimer;
public final UUID rsID;
public final byte[] columnFamily;
public final String rowType;
public final Configuration conf;
public boolean tableExists = false;
private class TimeValue {
private long time;
private boolean stale;
private TimeValue(long time) {
this.time = time;
this.stale = false;
}
}
public TableUpdater(String rowType, final Configuration conf) {
this.columnFamily = Bytes.toBytes(ReplicationConstants.ReplicationStatusTool.TIME_FAMILY);
this.rowType = rowType;
this.rsID = UUID.randomUUID();
this.conf = conf;
String configuredDelay = conf.get(ReplicationConstants.ReplicationStatusTool.REPLICATION_DELAY);
String configuredPeriod = conf.get(ReplicationConstants.ReplicationStatusTool.REPLICATION_PERIOD);
long delay = (configuredDelay != null)
? new Long(configuredDelay)
: ReplicationConstants.ReplicationStatusTool.REPLICATION_DELAY_DEFAULT;
long period = (configuredPeriod != null)
? new Long(configuredPeriod)
: ReplicationConstants.ReplicationStatusTool.REPLICATION_PERIOD_DEFAULT;
cachedUpdates = new HashMap<>();
setupTimer(delay, period);
}
/**
* Synchronized method used by replication status tool TableUpdate class to add timestamps
* from coprocessors.
* @param regionName is the key for the Map
* @param time is the value for the Map
*/
public void updateTime(String regionName, long time) throws IOException {
synchronized (cachedUpdatesLock) {
TimeValue timeValue = cachedUpdates.get(regionName);
if (timeValue == null) {
cachedUpdates.put(regionName, new TimeValue(time));
} else if (time > timeValue.time) {
timeValue.time = time;
timeValue.stale = false;
}
}
}
protected final byte[] getRowKey(String regionName) {
ReplicationStatusKey replicationStatusKey = new ReplicationStatusKey(rowType, regionName, rsID);
return replicationStatusKey.getKey();
}
public void setupTimer(long delay, long period) {
updateTimer = new Timer("UpdateTimer");
TimerTask updateTask = new TimerTask() {
@Override
public void run() {
try {
if (!tableExists) {
createTableIfNotExists(conf);
tableExists = true;
}
Map<String, Long> updatesToWrite;
synchronized (cachedUpdatesLock) {
// Make a copy of new updates so HBase write can happen outside of the synchronized block
updatesToWrite = getNewEntries(cachedUpdates);
}
if (!updatesToWrite.isEmpty()) {
LOG.debug("Update Replication State table now. {} entries.", updatesToWrite.size());
writeState(updatesToWrite);
}
} catch (IOException ioe) {
LOG.error("Put to Replication State Table failed.", ioe);
}
}
};
updateTimer.scheduleAtFixedRate(updateTask, delay, period);
}
private Map<String, Long> getNewEntries(Map<String, TimeValue> updateMap) {
Map<String, Long> cleanMap = new HashMap<>();
for (Map.Entry<String, TimeValue> entry : updateMap.entrySet()) {
if (!entry.getValue().stale) {
cleanMap.put(entry.getKey(), entry.getValue().time);
entry.getValue().stale = true;
}
}
return cleanMap;
}
public void cancelTimer() throws IOException {
LOG.info("Cancelling Update Timer now.");
synchronized (cachedUpdatesLock) {
writeState(getNewEntries(cachedUpdates));
}
updateTimer.cancel();
}
protected abstract void writeState(Map<String, Long> cachedUpdates) throws IOException;
protected abstract void createTableIfNotExists(Configuration conf) throws IOException;
} |
Java | public final class ServiceIndex implements Route {
/**
* Services.
*/
private final Iterable<Service> services;
/**
* Ctor.
*
* @param services Services.
*/
public ServiceIndex(final Iterable<Service> services) {
this.services = services;
}
@Override
public String path() {
return "/";
}
@Override
public Resource resource(final String path) {
final Resource resource;
if (path.equals("/index.json")) {
resource = new Index();
} else {
resource = new Absent();
}
return resource;
}
/**
* Services index JSON "/index.json".
*
* @since 0.1
*/
private final class Index implements Resource {
@Override
public Response get(final Headers headers) {
final JsonArrayBuilder resources = Json.createArrayBuilder();
for (final Service service : ServiceIndex.this.services) {
resources.add(
Json.createObjectBuilder()
.add("@id", service.url())
.add("@type", service.type())
);
}
final JsonObject json = Json.createObjectBuilder()
.add("version", "3.0.0")
.add("resources", resources)
.build();
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonWriter writer = Json.createWriter(out)) {
writer.writeObject(json);
out.flush();
return new RsWithStatus(
new RsWithBodyNoHeaders(out.toByteArray()),
RsStatus.OK
);
} catch (final IOException ex) {
throw new IllegalStateException("Failed to serialize JSON to bytes", ex);
}
}
@Override
public Response put(
final Headers headers,
final Publisher<ByteBuffer> body) {
return new RsWithStatus(RsStatus.METHOD_NOT_ALLOWED);
}
}
} |
Java | public class AddressModel {
final String address;
final String publicKey;
final String privateKey;
public AddressModel(String address, String publicKey, String privateKey) {
this.address = address;
this.publicKey = publicKey;
this.privateKey = privateKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AddressModel that = (AddressModel) o;
return Objects.equals(address, that.address) &&
Objects.equals(publicKey, that.publicKey) &&
Objects.equals(privateKey, that.privateKey);
}
@Override
public int hashCode() {
return Objects.hash(address, publicKey, privateKey);
}
@Override
public String toString() {
return "AddressModel{" +
"address='" + address + '\'' +
", publicKey='" + publicKey + '\'' +
", privateKey='" + privateKey + '\'' +
'}';
}
} |
Java | @SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class PlayerRecord extends UpdatableRecordImpl<PlayerRecord> implements Record2<String, LocalDate> {
private static final long serialVersionUID = -2035658545;
/**
* Setter for <code>fwdb.player.username</code>.
*/
public void setUsername(String value) {
set(0, value);
}
/**
* Getter for <code>fwdb.player.username</code>.
*/
public String getUsername() {
return (String) get(0);
}
/**
* Setter for <code>fwdb.player.birthday</code>.
*/
public void setBirthday(LocalDate value) {
set(1, value);
}
/**
* Getter for <code>fwdb.player.birthday</code>.
*/
public LocalDate getBirthday() {
return (LocalDate) get(1);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<String> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
@Override
public Row2<String, LocalDate> fieldsRow() {
return (Row2) super.fieldsRow();
}
@Override
public Row2<String, LocalDate> valuesRow() {
return (Row2) super.valuesRow();
}
@Override
public Field<String> field1() {
return Player.PLAYER.USERNAME;
}
@Override
public Field<LocalDate> field2() {
return Player.PLAYER.BIRTHDAY;
}
@Override
public String component1() {
return getUsername();
}
@Override
public LocalDate component2() {
return getBirthday();
}
@Override
public String value1() {
return getUsername();
}
@Override
public LocalDate value2() {
return getBirthday();
}
@Override
public PlayerRecord value1(String value) {
setUsername(value);
return this;
}
@Override
public PlayerRecord value2(LocalDate value) {
setBirthday(value);
return this;
}
@Override
public PlayerRecord values(String value1, LocalDate value2) {
value1(value1);
value2(value2);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached PlayerRecord
*/
public PlayerRecord() {
super(Player.PLAYER);
}
/**
* Create a detached, initialised PlayerRecord
*/
public PlayerRecord(String username, LocalDate birthday) {
super(Player.PLAYER);
set(0, username);
set(1, birthday);
}
} |
Java | public class ModuleStatusView extends View {
private static final int EDIT_MODE_MODULE_COUNT = 8 ;
private static final int SHAPE_CIRCLE = 0;
float mOutlineWidth, mShapeSize,mSpacing,mRadius ;
int mOutlineColor ;
public Paint mPaintOutline;
Paint mPaintFill;
int fillColor;
int maxHorizontaleModules;
private int mShape;
public boolean[] getmModuleStatus() {
return mModuleStatus;
}
public void setmModuleStatus(boolean[] mModuleStatus) {
this.mModuleStatus = mModuleStatus;
}
private boolean[] mModuleStatus;
Rect[] mModuleRectangles;
public ModuleStatusView(Context context) {
super(context);
init(null, 0);
}
public ModuleStatusView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public ModuleStatusView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// TODO 6:
if(isInEditMode())
setupEditModeValues();
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.ModuleStatusView, defStyle, 0);
//config color attr
mOutlineColor = a.getColor(R.styleable.ModuleStatusView_outlineColor,Color.BLACK);
int shape = a.getInt(R.styleable.ModuleStatusView_shape,SHAPE_CIRCLE);
a.recycle();
/*
TODO (1)
*/
mOutlineWidth = 6f;
mShapeSize = 120f;
mSpacing = 135f;
mRadius = (mShapeSize - mOutlineWidth) / 2;
// setupModuleRectangles();
/*
TODO (3)
*/
mPaintOutline = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintOutline.setStyle(Paint.Style.STROKE);
mPaintOutline.setStrokeWidth(mOutlineWidth);
mPaintOutline.setColor(mOutlineColor);
/*
TODO (4)
color fill my round property
*/
fillColor = getContext().getResources().getColor(R.color.my_orange);
mPaintFill = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintFill.setStyle(Paint.Style.FILL);
mPaintFill.setColor(fillColor);
}
private void setupEditModeValues() {
boolean[] examples = new boolean[EDIT_MODE_MODULE_COUNT];
int middle = EDIT_MODE_MODULE_COUNT / 2;
for (int i = 0; i < middle; i++)
examples[i]= true;
setmModuleStatus(examples);
}
/*
TODO (2)
creation of rectangle
*/
private void setupModuleRectangles(int width) {
//TODO 9 adapt to grid given responsive style width new width
int avialableWidth = width - getPaddingRight() - getPaddingLeft();
int horizontalModulesThatCanFit = (int)(avialableWidth / (mShapeSize + mSpacing)) ;
int maxHorizontalModules = Math.min(horizontalModulesThatCanFit,mModuleStatus.length);
mModuleRectangles = new Rect[mModuleStatus.length];
// i represent de current module
for (int i = 0; i < mModuleRectangles.length ; i++) {
//TODO 8 adapt to grid content positionning
int colunm = i % maxHorizontalModules;
int row = i / maxHorizontalModules;
//int x = getPaddingLeft() + (int)(i*(mShapeSize + mSpacing));
//int y = getPaddingTop();
int x = getPaddingLeft() + (int)(colunm*(mShapeSize + mSpacing));
int y = getPaddingTop() + (int)(row*(mShapeSize + mSpacing));
mModuleRectangles[i] = new Rect(x,y,(int) mShapeSize,(int) mShapeSize);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
setupModuleRectangles(w);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// TODO (5):
for (int i = 0; i < mModuleRectangles.length ; i++) {
if (mShape == SHAPE_CIRCLE){
float x = mModuleRectangles[i].centerX();
float y = mModuleRectangles[i].centerY();
if (mModuleStatus[i])
canvas.drawCircle(x,y,mRadius,mPaintFill);
canvas.drawCircle(x,y,mRadius,mPaintOutline);
} else{
drawSquare(canvas,i);
}
}
}
private void drawSquare(Canvas canvas, int i) {
// canvas.drawRect();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desireWidth=0,desireHeight=0;
//TODO 7
int specWidth = MeasureSpec.getSize(widthMeasureSpec);
int avialableWidth = specWidth -getPaddingLeft() - getPaddingRight();
int horizontalModuleThatCanFit = (int)(avialableWidth / (mShapeSize + mSpacing)) ;
maxHorizontaleModules = Math.min(horizontalModuleThatCanFit,mModuleStatus.length);
//desireWidth = (int)(mModuleStatus.length*(mShapeSize + mSpacing) - mSpacing);
desireWidth = (int)(maxHorizontaleModules*(mShapeSize + mSpacing) - mSpacing);
desireWidth+=(getPaddingLeft()+ getPaddingRight());
//number pf rows
int rows = ((mModuleStatus.length -1 )/ maxHorizontaleModules) +1;
desireHeight =(int)(rows*(mShapeSize + mSpacing) - mSpacing);
int width = resolveSizeAndState(desireWidth,widthMeasureSpec,0);
int height = resolveSizeAndState(desireHeight,heightMeasureSpec,0);
setMeasuredDimension(width,height);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
int moduleIndex =findItemAtpoint(event.getX(),event.getY());
OnModuleSelected(moduleIndex);
return true;
}
return super.onTouchEvent(event);
}
private void OnModuleSelected(int moduleIndex) {
if(moduleIndex == GLES30.GL_INVALID_INDEX)
return;
mModuleStatus[moduleIndex] = ! mModuleStatus[moduleIndex];
//redraw view
invalidate();
}
private int findItemAtpoint(float x, float y) {
int moduleIndex = GLES30.GL_INVALID_INDEX;
for (int i = 0 ; i < mModuleRectangles.length; i++){
if(mModuleRectangles[i].contains((int)x,(int)y)){
moduleIndex = i;
break;
}
}
return moduleIndex;
}
} |
Java | public class MappingConfigurationSearchResultsTable extends Table
{
private static final long serialVersionUID = -7119129093455804443L;
/**
* Constructor
*
* @param listener
*/
public MappingConfigurationSearchResultsTable(MappingSearchResultTableItemClickListener listener)
{
init(listener);
}
/**
* Helper method to initialise the component.
*
* @param listener
*/
private void init(MappingSearchResultTableItemClickListener listener)
{
this.setSizeFull();
addContainerProperty("Client", String.class, null);
addContainerProperty("Type", String.class, null);
addContainerProperty("Source Context", String.class, null);
addContainerProperty("Target Context", String.class, null);
addContainerProperty("Number of Mappings", String.class, null);
addContainerProperty("Last Updated By", String.class, null);
addContainerProperty("Last Updated", String.class, null);
addContainerProperty("Delete", Button.class, null);
addContainerProperty("Download", Button.class, null);
setColumnExpandRatio("Client", .1f);
setColumnExpandRatio("Type", .15f);
setColumnExpandRatio("Source Context", .15f);
setColumnExpandRatio("Target Context", .15f);
setColumnExpandRatio("Number of Mappings", .1f);
setColumnExpandRatio("Last Updated By", .1f);
setColumnExpandRatio("Last Updated", .10f);
setColumnExpandRatio("Delete", .05f);
setColumnExpandRatio("Download", .05f);
this.addItemClickListener(listener);
this.setCellStyleGenerator(new IkasanSmallCellStyleGenerator());
}
} |
Java | public class JsonFormatter extends ExtFormatter {
@Override
public String format(final ExtLogRecord logRecord) {
return toJsonObject(logRecord).build();
}
private Json.JsonObjectBuilder toJsonObject(ExtLogRecord logRecord) {
String formattedMessage = formatMessage(logRecord);
Json.JsonObjectBuilder jsonObject = Json.object();
jsonObject.put(TYPE, LOG_LINE);
if (logRecord.getLoggerName() != null) {
jsonObject.put(LOGGER_NAME_SHORT, getShortFullClassName(logRecord.getLoggerName(), ""));
jsonObject.put(LOGGER_NAME, logRecord.getLoggerName());
}
if (logRecord.getLoggerClassName() != null) {
jsonObject.put(LOGGER_CLASS_NAME, logRecord.getLoggerClassName());
}
if (logRecord.getHostName() != null) {
jsonObject.put(HOST_NAME, logRecord.getHostName());
}
if (logRecord.getLevel() != null) {
jsonObject.put(LEVEL, logRecord.getLevel().getName());
}
if (formattedMessage != null) {
jsonObject.put(FORMATTED_MESSAGE, formattedMessage);
}
if (logRecord.getMessage() != null) {
jsonObject.put(MESSAGE, logRecord.getMessage());
}
jsonObject.put(SOURCE_LINE_NUMBER, logRecord.getSourceLineNumber());
if (logRecord.getSourceClassName() != null) {
String justClassName = getJustClassName(logRecord.getSourceClassName());
jsonObject.put(SOURCE_CLASS_NAME_FULL_SHORT, getShortFullClassName(logRecord.getSourceClassName(), justClassName));
jsonObject.put(SOURCE_CLASS_NAME_FULL, logRecord.getSourceClassName());
jsonObject.put(SOURCE_CLASS_NAME, justClassName);
}
if (logRecord.getSourceFileName() != null) {
jsonObject.put(SOURCE_FILE_NAME, logRecord.getSourceFileName());
}
if (logRecord.getSourceMethodName() != null) {
jsonObject.put(SOURCE_METHOD_NAME, logRecord.getSourceMethodName());
}
if (logRecord.getThrown() != null) {
jsonObject.put(STACKTRACE, getStacktraces(logRecord.getThrown()));
}
jsonObject.put(THREAD_ID, logRecord.getThreadID());
jsonObject.put(THREAD_NAME, logRecord.getThreadName());
jsonObject.put(PROCESS_ID, logRecord.getProcessId());
jsonObject.put(PROCESS_NAME, logRecord.getProcessName());
jsonObject.put(TIMESTAMP, logRecord.getMillis());
jsonObject.put(SEQUENCE_NUMBER, logRecord.getSequenceNumber());
return jsonObject;
}
private Json.JsonArrayBuilder getStacktraces(Throwable t) {
List<String> traces = new LinkedList<>();
addStacktrace(traces, t);
Json.JsonArrayBuilder jsonArray = Json.array();
traces.forEach((trace) -> {
jsonArray.add(trace);
});
return jsonArray;
}
private void addStacktrace(List<String> traces, Throwable t) {
traces.add(getStacktrace(t));
if (t.getCause() != null)
addStacktrace(traces, t.getCause());
}
private String getStacktrace(Throwable t) {
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
t.printStackTrace(pw);
return sw.toString();
} catch (IOException ex) {
return null;
}
}
private String getJustClassName(String fullName) {
int lastDot = fullName.lastIndexOf(DOT) + 1;
return fullName.substring(lastDot);
}
private String getShortFullClassName(String fullName, String justClassName) {
String[] parts = fullName.split("\\" + DOT);
try (StringWriter buffer = new StringWriter()) {
for (int i = 0; i < parts.length - 1; i++) {
String part = parts[i];
if (part.equals(justClassName) || part.length() < 3) {
buffer.write(part);
} else {
buffer.write(part.substring(0, 3));
}
buffer.write(DOT);
}
buffer.write(parts[parts.length - 1]);
return buffer.toString();
} catch (IOException ex) {
return fullName;
}
}
private static final String TYPE = "type";
private static final String LEVEL = "level";
private static final String MESSAGE = "message";
private static final String FORMATTED_MESSAGE = "formattedMessage";
private static final String LOGGER_NAME_SHORT = "loggerNameShort";
private static final String LOGGER_NAME = "loggerName";
private static final String LOGGER_CLASS_NAME = "loggerClassName";
private static final String HOST_NAME = "hostName";
private static final String SOURCE_LINE_NUMBER = "sourceLineNumber";
private static final String SOURCE_CLASS_NAME_FULL = "sourceClassNameFull";
private static final String SOURCE_CLASS_NAME_FULL_SHORT = "sourceClassNameFullShort";
private static final String SOURCE_CLASS_NAME = "sourceClassName";
private static final String SOURCE_FILE_NAME = "sourceFileName";
private static final String SOURCE_METHOD_NAME = "sourceMethodName";
private static final String THREAD_ID = "threadId";
private static final String THREAD_NAME = "threadName";
private static final String PROCESS_ID = "processId";
private static final String PROCESS_NAME = "processName";
private static final String TIMESTAMP = "timestamp";
private static final String STACKTRACE = "stacktrace";
private static final String SEQUENCE_NUMBER = "sequenceNumber";
private static final String DOT = ".";
private static final String LOG_LINE = "logLine";
} |
Java | public class CommandLineTokenizer {
private final char[] buffer;
private int pos;
private static final char ESCAPE_CHAR = '\\';
private final List<String> args = new ArrayList<>();
public CommandLineTokenizer(String value) {
this.buffer = value.toCharArray();
tokenize();
}
public List<String> getArgs() {
return Collections.unmodifiableList(args);
}
private void tokenize() {
while (pos < buffer.length) {
eatWhiteSpace();
if (pos < buffer.length) {
eatArg();
}
}
}
private void eatWhiteSpace() {
while (pos < buffer.length && buffer[pos] == ' ') {
pos++;
}
}
private void eatArg() {
char endDelimiter;
if (buffer[pos] == '\'' || buffer[pos] == '"') {
endDelimiter = buffer[pos++];
}
else {
endDelimiter = ' ';
}
StringBuilder sb = new StringBuilder();
while (pos < buffer.length && buffer[pos] != endDelimiter) {
if (buffer[pos] == ESCAPE_CHAR) {
sb.append(processCharacterEscapeCodes(endDelimiter));
}
else {
sb.append(buffer[pos++]);
}
}
if (pos == buffer.length && endDelimiter != ' ') {
throw new IllegalStateException(String.format("Ran out of input in [%s], expected closing [%s]", new String(buffer), endDelimiter));
}
else if (endDelimiter != ' ' && buffer[pos] == endDelimiter) {
pos++;
}
args.add(sb.toString());
}
/**
* When the escape character is encountered, consume and return the escaped sequence. Note that depending on which
* end delimiter is currently in use, not all combinations need to be escaped
* @param endDelimiter the current endDelimiter
*/
private char processCharacterEscapeCodes(char endDelimiter) {
pos++;
if (pos >= buffer.length) {
throw new IllegalStateException("Ran out of input in escape sequence");
}
if (buffer[pos] == ESCAPE_CHAR) {
pos++; // consume the second escape char
return ESCAPE_CHAR;
}
else if (buffer[pos] == endDelimiter) {
pos++;
return endDelimiter;
}
else {
// Not an actual escape. Do not increment pos,
// and return the \ we consumed at the very beginning
return ESCAPE_CHAR;
}
}
} |
Java | public class OnBoardAntennaInterSatellitesPhaseModifier implements EstimationModifier<InterSatellitesPhase> {
/** Position of the Antenna Phase Center in satellite 1 frame. */
private final Vector3D antennaPhaseCenter1;
/** Position of the Antenna Phase Center in satellite 2 frame. */
private final Vector3D antennaPhaseCenter2;
/** Simple constructor.
* @param antennaPhaseCenter1 position of the Antenna Phase Center in satellite 1 frame
* (i.e. the satellite which receives the signal and performs the measurement)
* @param antennaPhaseCenter2 position of the Antenna Phase Center in satellite 2 frame
* (i.e. the satellite which simply emits the signal in the one-way
* case, or reflects the signal in the two-way case)
*/
public OnBoardAntennaInterSatellitesPhaseModifier(final Vector3D antennaPhaseCenter1,
final Vector3D antennaPhaseCenter2) {
this.antennaPhaseCenter1 = antennaPhaseCenter1;
this.antennaPhaseCenter2 = antennaPhaseCenter2;
}
/** {@inheritDoc} */
@Override
public List<ParameterDriver> getParametersDrivers() {
return Collections.emptyList();
}
@Override
public void modify(final EstimatedMeasurement<InterSatellitesPhase> estimated) {
// The participants are satellite 2 at emission, satellite 1 at reception
final TimeStampedPVCoordinates[] participants = estimated.getParticipants();
final AbsoluteDate emissionDate = participants[0].getDate();
final AbsoluteDate receptionDate = participants[1].getDate();
// transforms from spacecraft to inertial frame at emission/reception dates
final SpacecraftState localState = estimated.getStates()[0];
final SpacecraftState receptionState = localState.shiftedBy(receptionDate.durationFrom(localState.getDate()));
final Transform receptionSpacecraftToInert = receptionState.toTransform().getInverse();
final SpacecraftState remoteState = estimated.getStates()[1];
final SpacecraftState emissionState = remoteState.shiftedBy(emissionDate.durationFrom(remoteState.getDate()));
final Transform emissionSpacecraftToInert = emissionState.toTransform().getInverse();
// Compute the geometrical value of the inter-satellites range directly from participants positions.
final Vector3D pSpacecraftReception = receptionSpacecraftToInert.transformPosition(Vector3D.ZERO);
final Vector3D pSpacecraftEmission = emissionSpacecraftToInert.transformPosition(Vector3D.ZERO);
final double interSatellitesRangeUsingSpacecraftCenter = Vector3D.distance(pSpacecraftEmission, pSpacecraftReception);
// Compute the geometrical value of the range replacing
// The spacecraft positions with antenna phase center positions
final Vector3D pAPCReception = receptionSpacecraftToInert.transformPosition(antennaPhaseCenter1);
final Vector3D pAPCEmission = emissionSpacecraftToInert.transformPosition(antennaPhaseCenter2);
final double interSatellitesRangeUsingAntennaPhaseCenter = Vector3D.distance(pAPCEmission, pAPCReception);
// Get the estimated value before this modifier is applied
final double[] value = estimated.getEstimatedValue();
// Modify the phase value by applying measurement wavelength
final double wavelength = estimated.getObservedMeasurement().getWavelength();
value[0] += (interSatellitesRangeUsingAntennaPhaseCenter - interSatellitesRangeUsingSpacecraftCenter) / wavelength;
estimated.setEstimatedValue(value);
}
} |
Java | public class TagsContainKeywordsPredicate implements Predicate<Contact> {
private final List<String> keywords;
public TagsContainKeywordsPredicate(List<String> keywords) {
this.keywords = keywords;
}
@Override
public boolean test(Contact contact) {
return keywords.stream()
.allMatch(keyword -> contact.getTags()
.toString()
.toLowerCase()
.contains(keyword.toLowerCase()));
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof TagsContainKeywordsPredicate // instanceof handles nulls
&& keywords.equals(((TagsContainKeywordsPredicate) other).keywords)); // state check
}
} |
Java | public class EchoBean {
public String echo(Object... params) {
StringBuilder sb = new StringBuilder();
for (Object param : params) {
sb.append(":");
sb.append(param.toString());
}
return sb.toString();
}
} |
Java | public class AssetURLConnection extends PiggybackURLConnection<AssetURLContext> {
public AssetURLConnection(final URL url, final AssetURLContext implHelper) {
super(url, implHelper);
}
@Override
public String getEntryName() throws IOException {
if(!connected) {
throw new IOException("not connected");
}
final String urlPath ;
if(subConn instanceof JarURLConnection) {
urlPath = ((JarURLConnection)subConn).getEntryName();
} else {
urlPath = subConn.getURL().getPath();
}
if(urlPath.startsWith(AssetURLContext.assets_folder)) {
return urlPath.substring(AssetURLContext.assets_folder.length());
} else {
return urlPath;
}
}
} |
Java | @SuppressWarnings("serial")
public class PinnacleException extends IOException {
enum TYPE {
CONNECTION_FAILED, ERROR_RETURNED, PARAMETER_INVALID, JSON_UNPARSABLE;
}
private TYPE errorType;
public TYPE errorType() {
return this.errorType;
}
private String errorJson;
public String errorJson() {
return this.errorJson;
}
/*
* public GenericException parsedErrorJson () throws PinnacleException {
* return GenericException.parse(this.errorJson); }
*/
private int statusCode;
public int statusCode() {
return this.statusCode;
}
private String unparsableJson;
public String unparsableJson() {
return this.unparsableJson;
}
private PinnacleException(String message, TYPE errorType) {
super(message);
this.errorType = errorType;
}
static PinnacleException connectionFailed(String message) {
return new PinnacleException(message, TYPE.CONNECTION_FAILED);
}
static PinnacleException errorReturned(int statusCode, String errorJson) {
PinnacleException ex = new PinnacleException("API returned an error response:[" + statusCode + "] " + errorJson,
TYPE.ERROR_RETURNED);
ex.statusCode = statusCode;
ex.errorJson = errorJson;
return ex;
}
static PinnacleException parameterInvalid(String message) {
return new PinnacleException(message, TYPE.PARAMETER_INVALID);
}
static PinnacleException jsonUnparsable(String unparsableJson) {
PinnacleException ex = new PinnacleException("Couldn't parse JSON: " + unparsableJson, TYPE.JSON_UNPARSABLE);
ex.unparsableJson = unparsableJson;
return ex;
}
} |
Java | @ApiModel("Values of the XACML xPathExpression data-type are represented as JSON objects")
public class XPathExpression {
/**
* Provides the category of the {@link Category#content} where the expression applies
*/
@ApiModelProperty(
value = "Provides the category of the Content in Category where the expression applies.",
example = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource",
required = true
)
@JsonProperty("XPathCategory")
String xpathCategory;
/**
*
*/
@ApiModelProperty(
example = "[{\"Namespace\": \"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\"}]"
)
@JsonProperty("Namespaces")
final List<NamespaceDeclaration> namespaceDeclarations = new ArrayList<>();
/**
*
*/
@ApiModelProperty(
example = "md:record/md:patient/md:patientDoB",
required = true
)
@JsonProperty("XPath")
String xpath;
public XPathExpression(String xpathCategory, String xpath) {
this.xpathCategory = xpathCategory;
this.xpath = xpath;
}
public XPathExpression() {
}
public boolean addNamespaceDeclaration(String namespace) {
return namespaceDeclarations.add(new NamespaceDeclaration(namespace));
}
public boolean addNamespaceDeclaration(String namespace, String prefix) {
return namespaceDeclarations.add(new NamespaceDeclaration(namespace, prefix));
}
public String getXpathCategory() {
return this.xpathCategory;
}
public List<NamespaceDeclaration> getNamespaceDeclarations() {
return this.namespaceDeclarations;
}
public String getXpath() {
return this.xpath;
}
public void setXpathCategory(String xpathCategory) {
this.xpathCategory = xpathCategory;
}
public void setXpath(String xpath) {
this.xpath = xpath;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof XPathExpression)) return false;
final XPathExpression other = (XPathExpression) o;
if (!Objects.equals(this.getXpathCategory(), other.getXpathCategory())) return false;
if (!Objects.equals(this.getNamespaceDeclarations(), other.getNamespaceDeclarations())) return false;
return Objects.equals(this.getXpath(), other.getXpath());
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $xpathCategory = this.getXpathCategory();
result = result * PRIME + ($xpathCategory == null ? 43 : $xpathCategory.hashCode());
final Object $namespaceDeclarations = this.getNamespaceDeclarations();
result = result * PRIME + ($namespaceDeclarations == null ? 43 : $namespaceDeclarations.hashCode());
final Object $xpath = this.getXpath();
result = result * PRIME + ($xpath == null ? 43 : $xpath.hashCode());
return result;
}
public String toString() {
return "XPathExpression(xpathCategory=" + this.getXpathCategory() + ", namespaceDeclarations=" + this.getNamespaceDeclarations() + ", xpath=" + this.getXpath() + ")";
}
} |
Java | public class PropertiesFileHandlerTest {
private static final File PROPERTIES_FILE = new File(
PropertiesFileHandlerTest.class
.getClassLoader()
.getResource("properties/settings-test.properties")
.getFile()
);
private Settings settings;
private PropertiesHandler handler;
@BeforeClass
public static void registerSetStringConverter() {
StringConverterUtil.registerStringConverter(Set.class, new SetStringConverter<>(Locale.class));
StringConverterUtil.registerStringConverter(HashSet.class, new SetStringConverter<>(Locale.class));
}
@Before
public void setUp() throws Exception {
handler = new PropertiesFileHandler(PROPERTIES_FILE);
settings = new SettingsImpl(handler);
fillSettings(settings);
}
@Test
public void canStoreAndLoadUnboundedSettingFromFile() throws Exception {
// execute
settings.save();
settings.getUnboundedSetting(UNBOUNDED_SETTING).setValue("Not the default value");
// verify
assertThat(settings.getUnboundedSetting(UNBOUNDED_SETTING).getValue(), equalTo("Not the default value"));
settings.load();
assertThat(settings.getUnboundedSetting(UNBOUNDED_SETTING).getValue(), equalTo(DEFAULT_VALUE));
}
@Test
public void canStoreAndLoadRangeSettingFromFile() throws Exception {
// execute
settings.save();
settings.getRangeSetting(RANGE_SETTING).setValue(0.0);
// verify
assertThat(settings.getRangeSetting(RANGE_SETTING).getValue(), equalTo(0.0));
settings.load();
assertThat(settings.getRangeSetting(RANGE_SETTING).getValue(), equalTo(1.0));
}
@Test
public void canStoreAndLoadChoiceSettingFromFile() throws Exception {
// execute
settings.save();
settings.getChoiceSetting(CHOICE_SETTING).setValue(Color.BLUE);
// verify
assertThat(settings.getChoiceSetting(CHOICE_SETTING).getValue(), equalTo(Color.BLUE));
settings.load();
assertThat(settings.getChoiceSetting(CHOICE_SETTING).getValue(), equalTo(Color.BLACK));
}
@Test
public void canStoreAndLoadFileSettingFromFile() throws Exception {
// execute
settings.save();
settings.getFileSetting(FILE_SETTING).setValue(PROPERTIES_FILE);
// verify
assertThat(settings.getFileSetting(FILE_SETTING).getValue(), equalTo(PROPERTIES_FILE));
settings.load();
assertThat(settings.getFileSetting(FILE_SETTING).getValue(), equalTo(DEFAULT_FILE));
}
@Test
public void canStoreAndLoadMultiselectSettingFromFile() throws Exception {
// setup
final Set<Locale> oldSet = new HashSet<>(Arrays.asList(Locale.GERMANY, Locale.ENGLISH));
final Set<Locale> newSet = new HashSet<>(Collections.singletonList(Locale.GERMANY));
// execute
settings.save();
settings.<Locale>getMultiselectSetting(MULTISELECT_SETTING).setValue(newSet);
// verify
assertThat(settings.getMultiselectSetting(MULTISELECT_SETTING).getValue(), equalTo(newSet));
settings.load();
assertThat(settings.getMultiselectSetting(MULTISELECT_SETTING).getValue(), equalTo(oldSet));
}
@Test(expected = EasySettingsException.class)
public void throwsEasySettingsExceptionIfPathDoesntExistWhileLoading() throws Exception {
// setup
handler = new PropertiesFileHandler(new File("/this/directory/does/not/exist.properties"));
settings = new SettingsImpl(handler);
// execute
settings.load();
}
@Test(expected = EasySettingsException.class)
public void throwsEasySettingsExceptionIfPathDoesntExistWhileSaving() throws Exception {
// setup
handler = new PropertiesFileHandler(new File("/this/directory/does/not/exist.properties"));
settings = new SettingsImpl(handler);
// execute
settings.save();
}
} |
Subsets and Splits